import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { get_messages, send_message } from '@/api/chat'
import { ElMessage } from 'element-plus'
import { MessageManager, type MessageItem } from '@/utils/messageManager'

export interface ChatMessage extends MessageItem {
  // 继承MessageItem的所有属性
}

export interface ChatUser {
  sender_id: string
  sender_name: string
  sender_avatar?: string
  active?: boolean
}

export interface ChatState {
  messages: ChatMessage[]
  activeUser: ChatUser | null
  isLoading: boolean
  isConnected: boolean
  lastMessageTime: string | null
  unreadCount: number
}

export interface PollingConfig {
  baseInterval: number // 基础轮询间隔（毫秒）
  maxInterval: number   // 最大轮询间隔
  minInterval: number   // 最小轮询间隔
  backoffMultiplier: number // 退避倍数
  maxRetries: number    // 最大重试次数
}

export function useChat(appId: string, config?: Partial<PollingConfig>) {
  // 默认配置
  const defaultConfig: PollingConfig = {
    baseInterval: 1000,    // 1秒
    maxInterval: 30000,    // 30秒
    minInterval: 500,      // 0.5秒
    backoffMultiplier: 1.5,
    maxRetries: 3
  }
  
  const pollingConfig = { ...defaultConfig, ...config }
  
  // 自适应轮询配置
  const adaptiveConfig = {
    activeInterval: 1000,     // 用户活跃时的轮询间隔
    inactiveInterval: 5000,   // 用户不活跃时的轮询间隔
    idleInterval: 15000,      // 用户空闲时的轮询间隔
    inactiveThreshold: 30000, // 不活跃阈值（30秒）
    idleThreshold: 300000,    // 空闲阈值（5分钟）
    messageFrequencyThreshold: 5, // 消息频率阈值（每分钟）
    adaptiveEnabled: true     // 是否启用自适应轮询
  }
  
  // 性能优化配置
  const performanceConfig = {
    maxMessages: 1000,        // 最大消息数量
    cleanupThreshold: 1200,   // 清理阈值
    cleanupBatchSize: 200,    // 每次清理的消息数量
    debounceDelay: 100,       // 防抖延迟（毫秒）
    throttleDelay: 200,       // 节流延迟（毫秒）
    enableVirtualScroll: true, // 启用虚拟滚动
    enableLazyLoading: true   // 启用图片懒加载
  }
  
  // 消息管理器
  const messageManager = new MessageManager(1000)
  
  // 状态管理
  const state = reactive<ChatState>({
    messages: [],
    activeUser: null,
    isLoading: false,
    isConnected: true,
    lastMessageTime: null,
    unreadCount: 0
  })
  
  // 轮询相关状态
  const pollingState = reactive({
    timer: null as number | null,
    currentInterval: pollingConfig.baseInterval,
    retryCount: 0,
    isPolling: false,
    lastPollTime: 0,
    consecutiveEmptyPolls: 0
  })
  
  // 用户活动状态跟踪
  const activityState = reactive({
    lastActivity: Date.now(),
    lastMessageTime: Date.now(),
    messageCount: 0,
    messageFrequency: 0, // 每分钟消息数
    userStatus: 'active' as 'active' | 'inactive' | 'idle'
  })
  
  // 滚动和UI状态
  const uiState = reactive({
    isAutoScroll: true,
    isNearBottom: true,
    loadingMore: false,
    noMoreMessages: false
  })
  
  // 虚拟滚动状态
  const virtualScrollState = reactive({
    containerHeight: 400,
    itemHeight: 80,
    scrollTop: 0,
    visibleStart: 0,
    visibleEnd: 0
  })
  
  // 分页查询参数
  const queryParams = reactive({
    page: 1,
    page_size: 50,
    app_id: appId,
    user_id: ''
  })
  
  // 计算属性
  const hasActiveUser = computed(() => !!state.activeUser?.sender_id)
  const shouldPoll = computed(() => hasActiveUser.value) // 只要有活跃用户就应该轮询
  const hasMessages = computed(() => state.messages.length > 0)
  const isLoading = computed(() => uiState.loadingMore || pollingState.isPolling)
  const connectionStatus = computed(() => {
    if (!state.isConnected) return 'disconnected'
    if (pollingState.isPolling) return 'polling'
    return 'connected'
  })
  
  // 虚拟滚动计算属性
  const virtualScrollHeight = computed(() => {
    return state.messages.length * virtualScrollState.itemHeight
  })
  
  const virtualScrollOffset = computed(() => {
    return virtualScrollState.visibleStart * virtualScrollState.itemHeight
  })
  
  const visibleMessages = computed(() => {
    if (!performanceConfig.enableVirtualScroll || state.messages.length <= 50) {
      return state.messages
    }
    
    const start = Math.max(0, virtualScrollState.visibleStart)
    const end = Math.min(state.messages.length, virtualScrollState.visibleEnd)
    return state.messages.slice(start, end)
  })
  
  /**
   * 获取消息的唯一标识
   */
  function getMessageId(message: ChatMessage): string {
    return messageManager.getMessageId(message)
  }
  
  /**
   * 计算自适应轮询间隔
   */
  function calculateAdaptiveInterval(): number {
    if (!adaptiveConfig.adaptiveEnabled) {
      return pollingConfig.baseInterval
    }
    
    const now = Date.now()
    const timeSinceLastActivity = now - activityState.lastActivity
    const timeSinceLastMessage = now - activityState.lastMessageTime
    
    // 更新用户状态
    if (timeSinceLastActivity < adaptiveConfig.inactiveThreshold) {
      activityState.userStatus = 'active'
    } else if (timeSinceLastActivity < adaptiveConfig.idleThreshold) {
      activityState.userStatus = 'inactive'
    } else {
      activityState.userStatus = 'idle'
    }
    
    // 计算消息频率（每分钟消息数）
    const messageTimeWindow = 60000 // 1分钟
    if (timeSinceLastMessage < messageTimeWindow) {
      activityState.messageFrequency = activityState.messageCount / (timeSinceLastMessage / messageTimeWindow)
    } else {
      activityState.messageFrequency = 0
    }
    
    // 根据用户状态和消息频率确定轮询间隔
    let interval = pollingConfig.baseInterval
    
    switch (activityState.userStatus) {
      case 'active':
        interval = adaptiveConfig.activeInterval
        // 如果消息频率高，减少轮询间隔
        if (activityState.messageFrequency > adaptiveConfig.messageFrequencyThreshold) {
          interval = Math.max(500, interval * 0.5)
        }
        break
      case 'inactive':
        interval = adaptiveConfig.inactiveInterval
        break
      case 'idle':
        interval = adaptiveConfig.idleInterval
        break
    }
    
    return Math.min(interval, pollingConfig.maxInterval)
  }
  
  // 防抖函数
  const debounce = (func: Function, delay: number) => {
    let timeoutId: number | null = null
    return (...args: any[]) => {
      if (timeoutId) clearTimeout(timeoutId)
      timeoutId = window.setTimeout(() => func.apply(null, args), delay)
    }
  }
  
  // 节流函数
  const throttle = (func: Function, delay: number) => {
    let lastCall = 0
    return (...args: any[]) => {
      const now = Date.now()
      if (now - lastCall >= delay) {
        lastCall = now
        func.apply(null, args)
      }
    }
  }
  
  /**
   * 更新用户活动时间（防抖处理）
   */
  const updateUserActivity = debounce(() => {
     activityState.lastActivity = Date.now()
     activityState.userStatus = 'active'
     // 固定轮询模式下不需要重启轮询
   }, performanceConfig.debounceDelay)
   
   // 检查并清理旧消息
   const checkAndCleanupMessages = () => {
     const currentCount = messageManager.getStats().totalMessages
     if (currentCount > performanceConfig.cleanupThreshold) {
       const messagesToRemove = currentCount - performanceConfig.maxMessages
       messageManager.cleanup(messagesToRemove)
       state.messages = messageManager.getAllMessages()
       console.log(`清理了 ${messagesToRemove} 条旧消息，当前消息数: ${messageManager.getStats().totalMessages}`)
     }
   }
   
   // 内存监控
   const memoryMonitor = {
     lastCheck: Date.now(),
     checkInterval: 30000, // 30秒检查一次
     
     check() {
       const now = Date.now()
       if (now - this.lastCheck < this.checkInterval) return
       
       this.lastCheck = now
       const stats = messageManager.getStats()
       
       console.log('内存监控:', {
         消息数量: stats.totalMessages,
         缓存大小: stats.cacheSize,
         估算内存: `${(stats.memoryUsage / 1024 / 1024).toFixed(2)}MB`,
         虚拟滚动: performanceConfig.enableVirtualScroll ? '启用' : '禁用',
         懒加载: performanceConfig.enableLazyLoading ? '启用' : '禁用'
       })
       
       // 如果内存使用过高，强制清理
       if (stats.memoryUsage > 50 * 1024 * 1024) { // 50MB
         console.warn('内存使用过高，执行强制清理')
         checkAndCleanupMessages()
       }
     }
   }
  
  /**
   * 智能轮询策略
   */
  function calculateNextInterval(hasNewMessages: boolean, errorOccurred: boolean): number {
    if (errorOccurred) {
      // 发生错误时使用指数退避
      pollingState.currentInterval = Math.min(
        pollingState.currentInterval * pollingConfig.backoffMultiplier,
        pollingConfig.maxInterval
      )
    } else if (hasNewMessages) {
      // 有新消息时加快轮询
      pollingState.currentInterval = pollingConfig.minInterval
      pollingState.consecutiveEmptyPolls = 0
    } else {
      // 没有新消息时逐渐减慢轮询
      pollingState.consecutiveEmptyPolls++
      if (pollingState.consecutiveEmptyPolls > 3) {
        pollingState.currentInterval = Math.min(
          pollingState.currentInterval * 1.2,
          pollingConfig.maxInterval
        )
      }
    }
    
    return pollingState.currentInterval
  }
  
  /**
   * 获取最新消息
   */
  async function fetchLatestMessages(force: boolean = false): Promise<boolean> {
    if (!force && (pollingState.isPolling || !hasActiveUser.value)) {
      return false
    }
    
    if (!hasActiveUser.value) {
      return false
    }
    
    pollingState.isPolling = true
    pollingState.lastPollTime = Date.now()
    
    try {
      const query = {
        ...queryParams,
        page: 1, // 始终获取第一页的最新消息
        timestamp: state.lastMessageTime // 可选：传递时间戳进行增量更新
      }
      
      console.log('轮询获取消息:', query)
      
      const response = await get_messages(query)
      const newMessages = (response as any).list || []
      
      if (newMessages.length > 0) {
        // 处理消息内容
        const processedMessages = newMessages.map((msg: any) => {
          try {
            if (typeof msg.content === 'string') {
              try {
                msg.content = JSON.parse(msg.content)
              } catch (parseErr) {
                msg.content = { messages: msg.content }
              }
            }
          } catch (e) {
            // 保持原始内容（已在上方处理字符串情况）
          }
          return msg
        })
        
        // 使用MessageManager进行去重和管理
        const result = messageManager.addMessages(processedMessages)
        
        if (result.newMessages.length > 0) {
          // 更新状态中的消息列表
          const oldMessagesCount = state.messages.length
          state.messages = messageManager.getAllMessages()
          const newMessagesCount = state.messages.length
          
          console.log(`消息状态更新: 旧消息数量=${oldMessagesCount}, 新消息数量=${newMessagesCount}`)
          console.log('新增消息:', result.newMessages.map(m => ({ id: messageManager.getMessageId(m), content: m.content })))
          
          // 检查是否需要清理旧消息
          checkAndCleanupMessages()
          
          // 内存监控检查
          memoryMonitor.check()
          
          // 更新最后消息时间
          const latestMessage = result.newMessages[result.newMessages.length - 1]
          state.lastMessageTime = latestMessage.send_time
          
          // 如果用户不在底部，增加未读计数
          if (!uiState.isNearBottom) {
            state.unreadCount += result.newMessages.length
          }
          
          console.log(`添加了 ${result.newMessages.length} 条新消息，更新了 ${result.updatedMessages.length} 条消息`)
          console.log('消息管理器统计:', messageManager.getStats())
          console.log('当前消息列表长度:', state.messages.length)
          
          pollingState.retryCount = 0
          state.isConnected = true
          
          return true
        }
      }
      
      pollingState.retryCount = 0
      state.isConnected = true
      return false
      
    } catch (error) {
      console.error('获取消息失败:', error)
      pollingState.retryCount++
      
      if (pollingState.retryCount >= pollingConfig.maxRetries) {
        state.isConnected = false
        ElMessage.error('连接失败，请检查网络')
      }
      
      return false
    } finally {
      pollingState.isPolling = false
    }
  }
  
  /**
   * 启动轮询
   */
  function startPolling() {
    stopPolling()
    
    if (!shouldPoll.value) {
      return
    }
    
    console.log('启动固定1秒轮询消息')
    
    const poll = async () => {
      console.log(`开始轮询 - 用户: ${state.activeUser?.sender_name}, shouldPoll: ${shouldPoll.value}`)
      const hasNewMessages = await fetchLatestMessages()
      
      if (hasNewMessages) {
        activityState.messageCount++
        activityState.lastMessageTime = Date.now()
        console.log('轮询发现新消息，已更新状态')
      } else {
        console.log('轮询未发现新消息')
      }
      
      // 使用固定1秒轮询间隔
      const nextInterval = pollingConfig.baseInterval // 固定1秒
      
      console.log(`轮询状态: 固定间隔, 间隔: ${nextInterval}ms, 下次轮询: ${shouldPoll.value}`)
      
      if (shouldPoll.value) {
        pollingState.timer = setTimeout(poll, nextInterval)
      } else {
        console.log('停止轮询 - shouldPoll为false')
      }
    }
    
    // 立即执行一次，然后开始定时轮询
    poll()
  }
  
  /**
   * 停止轮询
   */
  function stopPolling() {
    if (pollingState.timer) {
      clearTimeout(pollingState.timer)
      pollingState.timer = null
      console.log('停止消息轮询')
    }
  }
  
  /**
   * 重置轮询状态
   */
  function resetPolling() {
    pollingState.currentInterval = pollingConfig.baseInterval
    pollingState.retryCount = 0
    pollingState.consecutiveEmptyPolls = 0
  }
  
  /**
   * 加载历史消息
   */
  async function loadHistoryMessages() {
    if (uiState.loadingMore || uiState.noMoreMessages || !hasActiveUser.value) {
      return
    }
    
    uiState.loadingMore = true
    
    try {
      queryParams.page++
      const response = await get_messages({ ...queryParams })
      const historyMessages = (response as any).list || []
      
      if (historyMessages.length > 0) {
        // 处理消息内容
        const processedMessages = historyMessages.map((msg: any) => {
          try {
            if (typeof msg.content === 'string') {
              try {
                msg.content = JSON.parse(msg.content)
              } catch (parseErr) {
                msg.content = { messages: msg.content }
              }
            }
          } catch (e) {
            // 保持原始内容（已在上方处理字符串情况）
          }
          return msg
        })
        
        // 使用MessageManager添加历史消息
        messageManager.addMessages(processedMessages)
        state.messages = messageManager.getAllMessages()
        
        // 检查是否还有更多消息
        if (historyMessages.length < queryParams.page_size) {
          uiState.noMoreMessages = true
        }
      } else {
        uiState.noMoreMessages = true
      }
    } catch (error) {
      console.error('加载历史消息失败:', error)
      queryParams.page-- // 回滚页码
    } finally {
      uiState.loadingMore = false
    }
  }
  
  /**
   * 发送消息
   */
  async function sendMessage(content: string, msgType: number = 1) {
    if (!hasActiveUser.value || !content.trim()) {
      return
    }
    
    // 更新用户活动
    updateUserActivity()
    
    const tempId = `temp_${Date.now()}_${Math.random()}`
    const tempMessage: ChatMessage = {
      _id: tempId,
      sender_id: 'current_user',
      sender_name: '我',
      content: { messages: content },
      msg_type: msgType,
      send_time: new Date().toISOString(),
      _sending: true,
      _failed: false,
      _local: true
    }
    
    // 使用MessageManager添加临时消息
    messageManager.addMessage(tempMessage)
    state.messages = messageManager.getAllMessages()
    
    try {
      const response = await send_message({
        app_id: appId,
        content,
        msg_type: msgType,
        to_user_id: state.activeUser!.sender_id
      })
      
      // 更新消息状态
      messageManager.markMessageSent(tempId, response as any)
      state.messages = messageManager.getAllMessages()
      
      // 立即强制轮询一次获取最新消息
      await fetchLatestMessages(true)
      
    } catch (error) {
      console.error('发送消息失败:', error)
      
      // 标记消息发送失败
      messageManager.markMessageFailed(tempId)
      state.messages = messageManager.getAllMessages()
      
      ElMessage.error('消息发送失败')
    }
  }
  
  /**
   * 重试发送失败的消息
   */
  async function retryMessage(messageId: string) {
    const message = state.messages.find(msg => getMessageId(msg) === messageId)
    if (!message || !message._failed) {
      return
    }
    
    message._sending = true
    message._failed = false
    
    try {
      const content = typeof message.content === 'object' 
        ? message.content.messages || message.content.content || ''
        : message.content
        
      await sendMessage(content, message.msg_type)
    } catch (error) {
      message._sending = false
      message._failed = true
    }
  }
  
  /**
   * 切换用户
   */
  function switchUser(user: ChatUser) {
    // 停止当前轮询
    stopPolling()
    
    // 重置状态
    state.activeUser = user
    state.messages = []
    state.lastMessageTime = null
    state.unreadCount = 0
    
    queryParams.user_id = user.sender_id
    queryParams.page = 1
    
    uiState.noMoreMessages = false
    resetPolling()
    
    // 加载初始消息
    loadInitialMessages()
  }
  
  /**
   * 加载初始消息
   */
  async function loadInitialMessages() {
    if (!hasActiveUser.value) return
    
    state.isLoading = true
    
    try {
      const response = await get_messages({ ...queryParams })
      const messages = (response as any).list || []
      
      if (messages.length > 0) {
        const processedMessages = messages.map((msg: any) => {
          try {
            if (typeof msg.content === 'string') {
              try {
                msg.content = JSON.parse(msg.content)
              } catch (parseErr) {
                msg.content = { messages: msg.content }
              }
            }
          } catch (e) {
            // 保持原始内容（已在上方处理字符串情况）
          }
          return msg
        })
        
        // 使用MessageManager初始化消息
        messageManager.addMessages(processedMessages)
        state.messages = messageManager.getAllMessages()
        
        // 设置最后消息时间
        if (processedMessages.length > 0) {
          state.lastMessageTime = processedMessages[processedMessages.length - 1].send_time
        }
        
        // 检查是否还有更多消息
        if (messages.length < queryParams.page_size) {
          uiState.noMoreMessages = true
        }
      }
      
      // 开始轮询
      startPolling()
      
    } catch (error) {
      console.error('加载初始消息失败:', error)
      ElMessage.error('加载消息失败')
    } finally {
      state.isLoading = false
    }
  }
  
  /**
   * 处理滚动事件（节流处理）
   */
  const handleScroll = throttle((scrollTop: number, scrollHeight: number, clientHeight: number) => {
    // 更新用户活动
    updateUserActivity()
    
    // 更新虚拟滚动状态
    if (performanceConfig.enableVirtualScroll && state.messages.length > 50) {
      virtualScrollState.scrollTop = scrollTop
      virtualScrollState.containerHeight = clientHeight
      
      const visibleCount = Math.ceil(clientHeight / virtualScrollState.itemHeight) + 2
      const startIndex = Math.floor(scrollTop / virtualScrollState.itemHeight)
      
      virtualScrollState.visibleStart = Math.max(0, startIndex - 1)
      virtualScrollState.visibleEnd = Math.min(
        state.messages.length,
        virtualScrollState.visibleStart + visibleCount
      )
    }
    
    const isNearBottom = scrollHeight - scrollTop - clientHeight < 50
    const wasNearBottom = uiState.isNearBottom
    
    uiState.isNearBottom = isNearBottom
    uiState.isAutoScroll = isNearBottom
    
    // 清除未读计数
    if (isNearBottom && state.unreadCount > 0) {
      state.unreadCount = 0
    }
    
    // 控制轮询
    // 保持轮询持续进行，与滚动位置无关
    if (shouldPoll.value && !pollingState.timer) {
      startPolling()
    }
    
    // 加载更多历史消息
    if (scrollTop <= 0) {
      loadHistoryMessages()
    }
  }, performanceConfig.throttleDelay)
  
  // 生命周期管理
  onMounted(() => {
    // 监听页面可见性变化
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        stopPolling()
      } else if (shouldPoll.value) {
        startPolling()
      }
    })
  })
  
  onUnmounted(() => {
    stopPolling()
  })
  
  // 重启轮询（用于自适应调整）
  const restartPolling = () => {
    if (pollingState.isPolling) {
      stopPolling()
      startPolling()
    }
  }

  return {
    // 状态
    state,
    pollingState,
    uiState,
    activityState,
    virtualScrollState,
    
    // 计算属性
    hasActiveUser,
    shouldPoll,
    hasMessages,
    isLoading,
    connectionStatus,
    virtualScrollHeight,
    virtualScrollOffset,
    visibleMessages,
    
    // 方法
    switchUser,
    sendMessage,
    retryMessage,
    loadHistoryMessages,
    handleScroll,
    startPolling,
    stopPolling,
    restartPolling,
    updateUserActivity,
    
    // 工具方法
    getMessageId,
    
    // 性能配置
    performanceConfig
  }
}