import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 本地Token管理器
 * 用于管理用户认证token和游戏角色token的本地存储
 */
export const useLocalTokenStore = defineStore('localToken', () => {
  // 状态
  const userToken = ref(localStorage.getItem('userToken') || null)
  const gameTokens = ref(JSON.parse(localStorage.getItem('gameTokens') || '{}'))
  const wsConnections = ref({}) // WebSocket连接状态
  
  // 计算属性
  const isUserAuthenticated = computed(() => !!userToken.value)
  const hasGameTokens = computed(() => Object.keys(gameTokens.value).length > 0)
  
  // 用户认证token管理
  const setUserToken = (token) => {
    userToken.value = token
    localStorage.setItem('userToken', token)
  }
  
  const clearUserToken = () => {
    userToken.value = null
    localStorage.removeItem('userToken')
  }
  
  // 游戏token管理
  const addGameToken = (roleId, tokenData) => {
    const newTokenData = {
      ...tokenData,
      roleId,
      createdAt: new Date().toISOString(),
      lastUsed: new Date().toISOString()
    }
    
    gameTokens.value[roleId] = newTokenData
    localStorage.setItem('gameTokens', JSON.stringify(gameTokens.value))
    
    return newTokenData
  }
  
  const getGameToken = (roleId) => {
    const token = gameTokens.value[roleId]
    if (token) {
      // 更新最后使用时间
      token.lastUsed = new Date().toISOString()
      localStorage.setItem('gameTokens', JSON.stringify(gameTokens.value))
    }
    return token
  }
  
  // 更新游戏token
    const updateGameToken = (roleId, tokenData) => {
        try {
            console.log(`[LocalTokenManager] 开始更新游戏token，角色ID: ${roleId}`)
            
            // 记录更新前的token数据
            const existingToken = gameTokens.value[roleId]
            console.log(`[LocalTokenManager] 更新前的token数据:`, {
                roleId,
                token: existingToken.token ? existingToken.token.substring(0, 20) + '...' : 'N/A',
                roleToken: existingToken.roleToken ? existingToken.roleToken.substring(0, 20) + '...' : 'N/A',
                lastRefreshed: existingToken.lastRefreshed
            })
            
            // 记录要更新的token数据
            console.log(`[LocalTokenManager] 要更新的token数据:`, {
                roleId,
                token: tokenData.token ? tokenData.token.substring(0, 20) + '...' : 'N/A',
                roleToken: tokenData.roleToken ? tokenData.roleToken.substring(0, 20) + '...' : 'N/A',
                lastRefreshed: tokenData.lastRefreshed
            })
            
            if (gameTokens.value[roleId]) {
                // 合并现有数据和新数据
                const updatedData = {
                    ...gameTokens.value[roleId],
                    ...tokenData,
                    id: roleId, // 确保ID正确
                    updatedAt: new Date().toISOString() // 更新时间戳
                }
                
                console.log(`[LocalTokenManager] 合并后的token数据:`, {
                    roleId,
                    token: updatedData.token ? updatedData.token.substring(0, 20) + '...' : 'N/A',
                    roleToken: updatedData.roleToken ? updatedData.roleToken.substring(0, 20) + '...' : 'N/A',
                    lastRefreshed: updatedData.lastRefreshed,
                    updatedAt: updatedData.updatedAt
                })
                
                // 更新状态
                gameTokens.value[roleId] = updatedData
                
                // 保存到localStorage
                localStorage.setItem('gameTokens', JSON.stringify(gameTokens.value))
                
                // 验证是否成功保存到localStorage
                const savedTokens = localStorage.getItem('gameTokens')
                const parsedTokens = savedTokens ? JSON.parse(savedTokens) : {}
                const savedToken = parsedTokens[roleId]
                
                console.log(`[LocalTokenManager] localStorage验证:`, {
                    roleId,
                    tokenSaved: !!savedToken,
                    roleTokenMatch: savedToken && savedToken.roleToken === updatedData.roleToken,
                    tokenMatch: savedToken && savedToken.token === updatedData.token
                })
                
                if (!savedToken || savedToken.roleToken !== updatedData.roleToken) {
                    console.error(`[LocalTokenManager] 错误: token未正确保存到localStorage`)
                    return false
                }
                
                console.log(`[LocalTokenManager] Token更新成功`)
                return true
            } else {
                console.error(`[LocalTokenManager] 错误: 找不到角色ID为 ${roleId} 的token数据`)
                return false
            }
        } catch (error) {
            console.error(`[LocalTokenManager] 更新游戏token失败:`, error)
            return false
        }
    }
  
  const removeGameToken = (roleId) => {
    delete gameTokens.value[roleId]
    localStorage.setItem('gameTokens', JSON.stringify(gameTokens.value))
    
    // 同时断开对应的WebSocket连接
    if (wsConnections.value[roleId]) {
      closeWebSocketConnection(roleId)
    }
  }
  
  const clearAllGameTokens = () => {
    // 关闭所有WebSocket连接
    Object.keys(wsConnections.value).forEach(roleId => {
      closeWebSocketConnection(roleId)
    })
    
    gameTokens.value = {}
    localStorage.removeItem('gameTokens')
  }
  
  // WebSocket连接管理 - 使用新的WsAgent
  const createWebSocketConnection = async (roleId, base64Token, customWsUrl = null) => {
    if (wsConnections.value[roleId]) {
      closeWebSocketConnection(roleId)
    }
    
    try {
      // 动态导入WebSocket客户端
      const { WsAgent } = await import('../utils/wsAgent.js')
      const { gameCommands } = await import('../utils/gameCommands.js')
      
      // 解析Base64获取实际Token
      let actualToken = base64Token
      
      // 尝试解析Base64获取实际token
      try {
        const cleanBase64 = base64Token.replace(/^data:.*base64,/, '').trim()
        const decoded = atob(cleanBase64)
        
        // 尝试解析为JSON获取token字段
        try {
          const tokenData = JSON.parse(decoded)
          actualToken = tokenData.token || tokenData.gameToken || decoded
        } catch {
          // 如果不是JSON，直接使用解码后的字符串
          actualToken = decoded
        }
      } catch (error) {
        console.warn('Base64解析失败，使用原始token:', error.message)
        actualToken = base64Token
      }
      
      // 创建WebSocket客户端实例
      const wsAgent = new WsAgent({
        heartbeatInterval: 2000,
        queueInterval: 50,
        channel: 'x', // 使用x通道
        autoReconnect: true,
        maxReconnectAttempts: 5
      })

      // 设置事件监听器
      wsAgent.onOpen = () => {
        console.log(`✅ WebSocket连接已建立: ${roleId}`)
        
        // 更新连接状态
        wsConnections.value[roleId].status = 'connected'
        wsConnections.value[roleId].connectedAt = new Date().toISOString()
        
        // 发送初始化命令
        setTimeout(() => {
          // 获取角色信息
          wsAgent.send(gameCommands.role_getroleinfo(0, 0, { roleId }))
          
          // 获取数据包版本
          wsAgent.send(gameCommands.system_getdatabundlever())
        }, 1000)
      }

      wsAgent.onMessage = (message) => {
        console.log(`📨 收到消息 [${roleId}]:`, message)
        
        // 处理不同类型的消息
        if (message.cmd) {
          handleGameMessage(roleId, message)
        }
      }

      wsAgent.onError = (error) => {
        console.error(`❌ WebSocket错误 [${roleId}]:`, error)
        // 添加更详细的错误信息
        const errorMessage = error.message || error.toString() || '未知WebSocket错误'
        console.error(`❌ WebSocket错误详情 [${roleId}]:`, {
          message: errorMessage,
          stack: error.stack,
          type: error.type,
          target: error.target,
          readyState: error.target?.readyState,
          bufferedAmount: error.target?.bufferedAmount
        })
        
        if (wsConnections.value[roleId]) {
          wsConnections.value[roleId].status = 'error'
          wsConnections.value[roleId].lastError = errorMessage
          // 保存错误时间戳
          wsConnections.value[roleId].lastErrorTime = new Date().toISOString()
        }
      }

      wsAgent.onClose = (event) => {
        console.log(`🔌 WebSocket连接已关闭 [${roleId}]:`, event.code, event.reason)
        if (wsConnections.value[roleId]) {
          wsConnections.value[roleId].status = 'disconnected'
        }
      }

      wsAgent.onReconnect = (attempt) => {
        console.log(`🔄 WebSocket重连中 [${roleId}] 第${attempt}次`)
        if (wsConnections.value[roleId]) {
          wsConnections.value[roleId].status = 'reconnecting'
          wsConnections.value[roleId].reconnectAttempt = attempt
        }
      }

      // 构建WebSocket URL
      const baseWsUrl = 'wss://xxz-xyzw.hortorgames.com/agent'
      const wsUrl = customWsUrl || WsAgent.buildUrl(baseWsUrl, {
        p: actualToken,
        e: 'x',
        lang: 'chinese'
      })
      
      // 保存连接信息
      wsConnections.value[roleId] = {
        agent: wsAgent,
        gameCommands,
        status: 'connecting',
        roleId,
        wsUrl,
        actualToken,
        createdAt: new Date().toISOString(),
        lastError: null,
        reconnectAttempt: 0
      }
      
      // 建立连接
      await wsAgent.connect(wsUrl)
      
      return wsAgent
    } catch (error) {
      console.error(`创建WebSocket连接失败 [${roleId}]:`, error)
      if (wsConnections.value[roleId]) {
        wsConnections.value[roleId].status = 'error'
        wsConnections.value[roleId].lastError = error.message
      }
      return null
    }
  }

  // 处理游戏消息
  const handleGameMessage = (roleId, message) => {
    const { cmd, body } = message
    
    switch (cmd) {
      case 'role_getroleinfo':
        console.log(`角色信息 [${roleId}]:`, body)
        break
        
      case 'system_getdatabundlever':
        console.log(`数据包版本 [${roleId}]:`, body)
        break
        
      case 'task_claimdailyreward':
        console.log(`每日任务奖励 [${roleId}]:`, body)
        break
        
      case 'system_signinreward':
        console.log(`签到奖励 [${roleId}]:`, body)
        break
        
      default:
        console.log(`未处理的消息 [${roleId}] ${cmd}:`, body)
    }
  }
  
  const closeWebSocketConnection = (roleId) => {
    const connection = wsConnections.value[roleId]
    if (connection) {
      // 如果是新的WsAgent实例
      if (connection.agent && typeof connection.agent.close === 'function') {
        connection.agent.close()
      }
      // 如果是旧的WebSocket实例
      else if (connection.connection && typeof connection.connection.close === 'function') {
        connection.connection.close()
      }
      
      delete wsConnections.value[roleId]
    }
  }
  
  const getWebSocketStatus = (roleId) => {
  return wsConnections.value[roleId]?.status || 'disconnected'
}

// 获取WebSocket错误信息
const getWebSocketError = (roleId) => {
  return wsConnections.value[roleId]?.lastError || null
}

// 获取WebSocket错误时间
const getWebSocketErrorTime = (roleId) => {
  return wsConnections.value[roleId]?.lastErrorTime || null
}

  // 发送游戏命令
  const sendGameCommand = (roleId, commandName, params = {}) => {
    const connection = wsConnections.value[roleId]
    if (!connection || !connection.agent) {
      console.warn(`角色 ${roleId} 的WebSocket连接不存在`)
      return false
    }

    if (connection.status !== 'connected') {
      console.warn(`角色 ${roleId} 的WebSocket未连接`)
      return false
    }

    try {
      const { gameCommands } = connection
      
      if (typeof gameCommands[commandName] === 'function') {
        const command = gameCommands[commandName](0, 0, params)
        connection.agent.send(command)
        console.log(`发送游戏命令 [${roleId}] ${commandName}:`, params)
        return true
      } else {
        console.error(`未知的游戏命令: ${commandName}`)
        return false
      }
    } catch (error) {
      console.error(`发送游戏命令失败 [${roleId}] ${commandName}:`, error)
      return false
    }
  }

  // 发送游戏命令并等待响应
  const sendGameCommandWithPromise = async (roleId, commandName, params = {}, timeout = 200) => {
    const connection = wsConnections.value[roleId]
    if (!connection || !connection.agent) {
      throw new Error(`角色 ${roleId} 的WebSocket连接不存在`)
    }

    if (connection.status !== 'connected') {
      throw new Error(`角色 ${roleId} 的WebSocket未连接`)
    }

    try {
      const { gameCommands } = connection
      
      if (typeof gameCommands[commandName] === 'function') {
        const response = await connection.agent.sendWithPromise({
          cmd: commandName,
          body: params,
          timeout
        })
        console.log(`游戏命令响应 [${roleId}] ${commandName}:`, response)
        return response
      } else {
        throw new Error(`未知的游戏命令: ${commandName}`)
      }
    } catch (error) {
      console.error(`发送游戏命令失败 [${roleId}] ${commandName}:`, error)
      throw error
    }
  }

  // 获取连接详细状态
  const getWebSocketDetails = (roleId) => {
    const connection = wsConnections.value[roleId]
    if (!connection) {
      return {
        status: 'disconnected',
        roleId,
        error: '连接不存在'
      }
    }

    return {
      status: connection.status,
      roleId: connection.roleId,
      wsUrl: connection.wsUrl,
      connectedAt: connection.connectedAt,
      createdAt: connection.createdAt,
      lastError: connection.lastError,
      reconnectAttempt: connection.reconnectAttempt,
      agentStatus: connection.agent ? connection.agent.getStatus() : null
    }
  }
  
  // 从bin文件刷新token
    const refreshTokenFromBin = async (roleId, tokenData = null) => {
        try {
            console.log(`[LocalTokenManager] 开始从bin文件刷新token，角色ID: ${roleId}`)
            
            // 如果没有传入tokenData，从store中获取
            if (!tokenData) {
                tokenData = gameTokens.value[roleId]
            }
            
            if (!tokenData) {
                console.error(`[LocalTokenManager] 错误: 找不到对应的Token数据`)
                return { success: false, error: '找不到对应的Token数据' }
            }
            
            if (!tokenData.binFileContent) {
                console.error(`[LocalTokenManager] 错误: 该Token没有bin文件内容`)
                return { success: false, error: '该Token没有bin文件内容' }
            }
            
            // 检查bin文件内容是否为空
            if (tokenData.binFileContent === '' || tokenData.binFileContent.length === 0) {
                console.error(`[LocalTokenManager] 错误: 该Token的bin文件内容为空`)
                return { success: false, error: '该Token的bin文件内容为空' }
            }

            // 记录原始token数据
            console.log(`[LocalTokenManager] 原始token数据:`, {
                roleId,
                token: tokenData.token ? tokenData.token.substring(0, 20) + '...' : 'N/A',
                roleToken: tokenData.roleToken ? tokenData.roleToken.substring(0, 20) + '...' : 'N/A',
                binFileContentLength: tokenData.binFileContent ? tokenData.binFileContent.length : 0
            })

            // 检查binFileContent是否为ArrayBuffer，如果是则转换为字符串
            let requestBody = tokenData.binFileContent
            if (tokenData.binFileContent instanceof ArrayBuffer) {
                const decoder = new TextDecoder('utf-8')
                requestBody = decoder.decode(tokenData.binFileContent)
                console.log(`[LocalTokenManager] 将ArrayBuffer转换为字符串，长度: ${requestBody.length}`)
            }
            
            console.log(`[LocalTokenManager] 请求体内容预览:`, requestBody.substring(0, 200) + '...')
            
            // 向咸鱼之王登录接口发送POST请求
            const loginUrl = 'https://xxz-xyzw.hortorgames.com/login/authuser?_seq=1'
            console.log(`[LocalTokenManager] 发送登录请求到: ${loginUrl}`)
            
            const response = await fetch(loginUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                },
                body: JSON.stringify({
                    bin: requestBody
                }),
            })
            
            console.log(`[LocalTokenManager] 响应状态:`, response.status, response.statusText)
            
            if (!response.ok) {
                console.error(`[LocalTokenManager] 登录请求失败: ${response.status} ${response.statusText}`)
                throw new Error(`登录请求失败: ${response.status} ${response.statusText}`)
            }
            
            const loginData = await response.json()
            console.log(`[LocalTokenManager] 登录响应完整数据:`, loginData)
            
            // 提取roleToken
            if (!loginData.roleToken) {
                console.error(`[LocalTokenManager] 响应中未找到roleToken，响应数据:`, loginData)
                throw new Error('响应中未找到roleToken')
            }
            
            const roleToken = loginData.roleToken
            console.log(`[LocalTokenManager] 成功从bin文件获取新的roleToken: ${roleToken.substring(0, 20)}...`)
            
            // 生成完整的Token数据和WSS连接参数
            const sessId = Date.now() * 1000 + Math.floor(Math.random() * 1000)
            const connId = Date.now()
            const tokenDataObj = {
                roleToken,
                sessId,
                connId,
                isRestore: 0,
            }
            
            console.log(`[LocalTokenManager] 生成的Token数据:`, tokenDataObj)
            
            // 创建完整的Token格式
            const tokenStr = JSON.stringify(tokenDataObj)
            const newToken = btoa(unescape(encodeURIComponent(tokenStr)))
            console.log(`[LocalTokenManager] Base64编码的Token: ${newToken.substring(0, 20)}...`)
            
            // 生成WebSocket URL
            const wsUrl = `wss://xxz-xyzw.hortorgames.com/agent?p=${encodeURIComponent(newToken)}&e=x&lang=chinese`
            
            console.log(`[LocalTokenManager] 更新前的Token数据:`, gameTokens.value[roleId])
            
            // 更新token数据
            const updateResult = updateGameToken(roleId, {
                token: newToken,
                wsUrl: wsUrl,
                lastRefreshed: new Date().toISOString(),
                roleToken: roleToken,
                sessId: sessId,
                connId: connId,
                binFileContent: tokenData.binFileContent, // 保留bin文件内容以便下次刷新
                importMethod: tokenData.importMethod || 'bin',
                server: tokenData.server || '咸鱼之王'
            })
            
            if (!updateResult) {
                console.error(`[LocalTokenManager] Token更新失败`)
                return { success: false, error: 'Token更新失败' }
            }
            
            console.log(`[LocalTokenManager] 更新后的Token数据:`, gameTokens.value[roleId])
            
            // 验证token是否正确保存
            const savedToken = localStorage.getItem('gameTokens')
            if (savedToken) {
                try {
                    const parsedTokens = JSON.parse(savedToken)
                    const currentToken = parsedTokens[roleId]
                    console.log(`[LocalTokenManager] localStorage中的Token数据:`, {
                        roleId,
                        token: currentToken.token ? currentToken.token.substring(0, 20) + '...' : 'N/A',
                        roleToken: currentToken.roleToken ? currentToken.roleToken.substring(0, 20) + '...' : 'N/A',
                        lastRefreshed: currentToken.lastRefreshed
                    })
                    
                    // 验证roleToken是否正确更新
                    if (currentToken.roleToken === roleToken) {
                        console.log(`[LocalTokenManager] roleToken已正确更新并保存到localStorage`)
                    } else {
                        console.error(`[LocalTokenManager] roleToken未正确更新，期望值: ${roleToken.substring(0, 20)}...，实际值: ${currentToken.roleToken ? currentToken.roleToken.substring(0, 20) + '...' : 'N/A'}`)
                        return { success: false, error: 'roleToken未正确更新' }
                    }
                } catch (error) {
                    console.error(`[LocalTokenManager] 解析localStorage中的token数据失败:`, error)
                    return { success: false, error: '解析token数据失败' }
                }
            } else {
                console.error(`[LocalTokenManager] localStorage中未找到gameTokens`)
                return { success: false, error: 'localStorage中未找到gameTokens' }
            }
            
            console.log(`[LocalTokenManager] Token刷新成功`)
            return {
                success: true,
                message: 'Token刷新成功',
                data: {
                    token: newToken,
                    wsUrl: wsUrl,
                    roleToken: roleToken
                }
            }
        } catch (error) {
            console.error(`[LocalTokenManager] 从bin文件刷新token失败:`, error)
            return {
                success: false,
                error: error.message
            }
        }
    }

  // 批量导入/导出功能
  const exportTokens = () => {
    return {
      userToken: userToken.value,
      gameTokens: gameTokens.value,
      exportedAt: new Date().toISOString()
    }
  }
  
  const importTokens = (tokenData) => {
    try {
      if (tokenData.userToken) {
        setUserToken(tokenData.userToken)
      }
      
      if (tokenData.gameTokens) {
        gameTokens.value = tokenData.gameTokens
        localStorage.setItem('gameTokens', JSON.stringify(gameTokens.value))
      }
      
      return { success: true, message: 'Token导入成功' }
    } catch (error) {
      console.error('Token导入失败:', error)
      return { success: false, message: '导入失败：数据格式错误' }
    }
  }
  
  // 清理过期token
  const cleanExpiredTokens = () => {
    const now = new Date()
    const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000)
    
    const cleanedTokens = {}
    let cleanedCount = 0
    
    Object.entries(gameTokens.value).forEach(([roleId, tokenData]) => {
      const lastUsed = new Date(tokenData.lastUsed || tokenData.createdAt)
      if (lastUsed > oneDayAgo) {
        cleanedTokens[roleId] = tokenData
      } else {
        cleanedCount++
        // 关闭对应的WebSocket连接
        if (wsConnections.value[roleId]) {
          closeWebSocketConnection(roleId)
        }
      }
    })
    
    gameTokens.value = cleanedTokens
    localStorage.setItem('gameTokens', JSON.stringify(gameTokens.value))
    
    return cleanedCount
  }
  
  // 初始化
  const initTokenManager = () => {
    // 从localStorage恢复数据
    const savedUserToken = localStorage.getItem('userToken')
    const savedGameTokens = localStorage.getItem('gameTokens')
    
    if (savedUserToken) {
      userToken.value = savedUserToken
    }
    
    if (savedGameTokens) {
      try {
        gameTokens.value = JSON.parse(savedGameTokens)
      } catch (error) {
        console.error('解析游戏token数据失败:', error)
        gameTokens.value = {}
      }
    }
    
    // 清理过期token
    cleanExpiredTokens()
  }
  
  return {
    // 状态
    userToken,
    gameTokens,
    wsConnections,
    
    // 计算属性
    isUserAuthenticated,
    hasGameTokens,
    
    // 用户token方法
    setUserToken,
    clearUserToken,
    
    // 游戏token方法
    addGameToken,
    getGameToken,
    updateGameToken,
    removeGameToken,
    clearAllGameTokens,
    
    // WebSocket方法
    createWebSocketConnection,
    closeWebSocketConnection,
    getWebSocketStatus,
    getWebSocketError,
    getWebSocketErrorTime,
    getWebSocketDetails,
    sendGameCommand,
    sendGameCommandWithPromise,
    
    // 工具方法
    exportTokens,
    importTokens,
    cleanExpiredTokens,
    initTokenManager,
    refreshTokenFromBin
  }
})