/**
 * 聊天状态管理
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { chatApi, fileApi } from '@/api'

export const useChatStore = defineStore('chat', () => {
  // 状态
  const messages = ref(new Map())
  const transfers = ref(new Map())
  const currentDeviceId = ref(null)
  const pendingFile = ref(null)
  const unreadCounts = ref(new Map())

  // 计算属性
  const currentMessages = computed(() => {
    if (!currentDeviceId.value) return []
    return messages.value.get(currentDeviceId.value) || []
  })

  const totalUnread = computed(() => {
    let count = 0
    unreadCounts.value.forEach(v => count += v)
    return count
  })

  // 设置当前聊天设备
  function setCurrentDevice(deviceId) {
    currentDeviceId.value = deviceId
    if (deviceId) {
      // 清除未读计数
      unreadCounts.value.set(deviceId, 0)
    }
  }

  // 加载聊天历史
  async function loadHistory(deviceId) {
    try {
      const history = await chatApi.getHistory(deviceId, 100, 0)
      // 按时间正序排列
      history.sort((a, b) => a.timestamp - b.timestamp)
      
      // 获取当前内存中的消息（可能包含实时接收但尚未持久化的消息）
      const existingMessages = messages.value.get(deviceId) || []
      
      // 合并历史记录和内存消息，使用 Map 去重（以 id 为 key）
      const messageMap = new Map()
      
      // 先添加数据库历史记录
      for (const msg of history) {
        messageMap.set(msg.id, msg)
      }
      
      // 再添加内存中的消息（覆盖同 id 的记录，保留新消息）
      for (const msg of existingMessages) {
        messageMap.set(msg.id, msg)
      }
      
      // 转换回数组并按时间排序
      const mergedMessages = Array.from(messageMap.values())
      mergedMessages.sort((a, b) => a.timestamp - b.timestamp)
      
      messages.value.set(deviceId, mergedMessages)
    } catch (error) {
      console.error('Failed to load chat history:', error)
    }
  }

  // 发送消息
  async function sendMessage(deviceId, content, type) {
    try {
      const message = await chatApi.sendMessage(deviceId, content, type)
      
      // 添加到本地消息列表
      const deviceMessages = messages.value.get(deviceId) || []
      deviceMessages.push(message)
      messages.value.set(deviceId, deviceMessages)

      return message
    } catch (error) {
      console.error('Failed to send message:', error)
      throw error
    }
  }

  // 接收消息
  function receiveMessage(message) {
    const deviceId = message.from
    const deviceMessages = messages.value.get(deviceId) || []
    
    // 避免重复
    if (!deviceMessages.find(m => m.id === message.id)) {
      deviceMessages.push(message)
      messages.value.set(deviceId, deviceMessages)

      // 如果不是当前聊天，增加未读计数
      if (currentDeviceId.value !== deviceId) {
        const count = unreadCounts.value.get(deviceId) || 0
        unreadCounts.value.set(deviceId, count + 1)
      }
    }
  }

  // 删除聊天历史
  async function deleteHistory(deviceId) {
    try {
      await chatApi.deleteHistory(deviceId)
      messages.value.delete(deviceId)
      unreadCounts.value.set(deviceId, 0)
    } catch (error) {
      console.error('Failed to delete chat history:', error)
      throw error
    }
  }

  // 选择文件
  async function selectFile() {
    try {
      const file = await fileApi.selectFile()
      pendingFile.value = file
      return file
    } catch (error) {
      console.error('Failed to select file:', error)
      return null
    }
  }

  // 发送文件
  async function sendFile(deviceId, file) {
    try {
      const transfer = await fileApi.sendFile(deviceId, file.fileId, file.path || '')
      transfers.value.set(transfer.fileId, transfer)
      return transfer
    } catch (error) {
      console.error('Failed to send file:', error)
      throw error
    }
  }

  // 更新传输进度
  function updateTransferProgress(event) {
    let transfer = transfers.value.get(event.fileId)
    if (transfer) {
      transfer.progress = event.progress
      transfer.status = event.status
      transfer.transferredBytes = event.transferredBytes
      // 如果有文件名和路径，更新它们（接收方）
      if (event.fileName) transfer.name = event.fileName
      if (event.localPath) transfer.localPath = event.localPath
    } else {
      // 如果传输记录不存在，创建一个临时记录（使用事件中的信息）
      transfers.value.set(event.fileId, {
        fileId: event.fileId,
        name: event.fileName || 'unknown',
        size: event.totalBytes,
        progress: event.progress,
        status: event.status,
        mimeType: 'application/octet-stream',
        fromDevice: '',
        toDevice: '',
        transferredBytes: event.transferredBytes,
        localPath: event.localPath,
        createdAt: Date.now(),
      })
    }
  }

  // 加载传输历史
  async function loadTransferHistory(deviceId, force = false) {
    try {
      const history = await fileApi.getHistory(deviceId, 50)
      history.forEach(transfer => {
        if (force) {
          // 强制更新（用于点击文件消息时查找）
          transfers.value.set(transfer.fileId, transfer)
        } else if (!transfers.value.has(transfer.fileId)) {
          // 只加载不存在的记录，避免覆盖实时进度数据
          transfers.value.set(transfer.fileId, transfer)
        }
      })
      return history
    } catch (error) {
      console.error('Failed to load transfer history:', error)
      return []
    }
  }

  // 打开文件位置
  async function openFileLocation(path) {
    try {
      await fileApi.openLocation(path)
    } catch (error) {
      console.error('Failed to open file location:', error)
    }
  }

  // 取消传输
  async function cancelTransfer(fileId) {
    try {
      await fileApi.cancelTransfer(fileId)
      const transfer = transfers.value.get(fileId)
      if (transfer) {
        transfer.status = 'cancelled'
      }
    } catch (error) {
      console.error('Failed to cancel transfer:', error)
    }
  }

  // 获取设备的未读消息数
  function getUnreadCount(deviceId) {
    return unreadCounts.value.get(deviceId) || 0
  }

  // 清除待发送文件
  function clearPendingFile() {
    pendingFile.value = null
  }

  return {
    // 状态
    messages,
    transfers,
    currentDeviceId,
    pendingFile,
    unreadCounts,
    // 计算属性
    currentMessages,
    totalUnread,
    // 方法
    setCurrentDevice,
    loadHistory,
    sendMessage,
    receiveMessage,
    deleteHistory,
    selectFile,
    sendFile,
    updateTransferProgress,
    loadTransferHistory,
    openFileLocation,
    cancelTransfer,
    getUnreadCount,
    clearPendingFile,
  }
})
