import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import envConfig from '@/config/env'

export const useUserStore = defineStore('user', () => {
  // 状态
  const accessToken = ref(localStorage.getItem('accessToken') || '')
  const refreshToken = ref(localStorage.getItem('refreshToken') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
  const tokenExpiresAt = ref(parseInt(localStorage.getItem('tokenExpiresAt') || '0'))
  
  // 防抖更新localStorage
  let updateTimer = null
  const debouncedUpdateStorage = (key, value) => {
    clearTimeout(updateTimer)
    updateTimer = setTimeout(() => {
      if (value === null || value === undefined || value === '') {
        localStorage.removeItem(key)
      } else {
        localStorage.setItem(key, typeof value === 'object' ? JSON.stringify(value) : value)
      }
    }, 100)
  }
  
  // 计算属性 - 使用缓存避免重复计算
  const isTokenExpired = computed(() => {
    if (!tokenExpiresAt.value) return true
    return Date.now() >= tokenExpiresAt.value
  })
  
  const isTokenExpiringSoon = computed(() => {
    if (!tokenExpiresAt.value) return false
    const fiveMinutes = 5 * 60 * 1000
    return Date.now() >= (tokenExpiresAt.value - fiveMinutes)
  })
  
  const isLoggedIn = computed(() => {
    return !!accessToken.value && !isTokenExpired.value
  })
  
  // Actions
  const setAuthData = (authData) => {
    if (!authData) return
    
    const { accessToken: newAccessToken, refreshToken: newRefreshToken, user, expiresIn } = authData
    
    // 批量更新状态，避免多次触发响应式更新
    const updates = []
    
    if (newAccessToken && newAccessToken !== accessToken.value) {
      accessToken.value = newAccessToken
      updates.push(['accessToken', newAccessToken])
    }
    
    if (newRefreshToken && newRefreshToken !== refreshToken.value) {
      refreshToken.value = newRefreshToken
      updates.push(['refreshToken', newRefreshToken])
    }
    
    if (user && JSON.stringify(user) !== JSON.stringify(userInfo.value)) {
      userInfo.value = user
      updates.push(['userInfo', user])
    }
    
    if (expiresIn) {
      const newExpiresAt = Date.now() + (expiresIn * 1000)
      if (newExpiresAt !== tokenExpiresAt.value) {
        tokenExpiresAt.value = newExpiresAt
        updates.push(['tokenExpiresAt', newExpiresAt])
      }
    }
    
    // 批量更新localStorage
    updates.forEach(([key, value]) => {
      debouncedUpdateStorage(key, value)
    })
  }
  
  // 兼容性方法 - 支持旧的setToken调用
  const setToken = (token) => {
    if (token) {
      accessToken.value = token
      debouncedUpdateStorage('accessToken', token)
    }
  }

  const logout = () => {
    // 清除状态
    accessToken.value = ''
    refreshToken.value = ''
    userInfo.value = null
    tokenExpiresAt.value = 0
    
    // 清除localStorage
    const keysToRemove = ['accessToken', 'refreshToken', 'userInfo', 'tokenExpiresAt']
    keysToRemove.forEach(key => localStorage.removeItem(key))
  }
  
  // 刷新访问令牌
  const refreshAccessToken = async () => {
    if (!refreshToken.value) {
      throw new Error('没有刷新令牌')
    }
    
    try {
      const response = await fetch(`${envConfig.baseURL}/auth/refresh`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          refreshToken: refreshToken.value
        })
      })
      
      if (!response.ok) {
        throw new Error('刷新令牌失败')
      }
      
      const data = await response.json()
      
      // 修复：检查响应格式，支持多种成功状态
      if (data.status === 'success' || data.code === 200 || data.success) {
        const authData = data.data || data
        setAuthData(authData)
        console.log('令牌刷新成功')
        return authData.accessToken
      } else {
        throw new Error(data.message || '刷新令牌失败')
      }
    } catch (error) {
      console.error('刷新访问令牌失败:', error)
      logout()
      throw error
    }
  }

  // 自动重新登录方法
  const autoRelogin = async () => {
    try {
      // 首先尝试使用refresh token刷新
      if (refreshToken.value) {
        try {
          await refreshAccessToken()
          return true
        } catch (error) {
          console.warn('使用refresh token刷新失败，尝试其他方式:', error)
        }
      }

      // 检查是否有记住的登录信息
      const rememberedUsername = localStorage.getItem('rememberedUsername')
      const rememberLogin = localStorage.getItem('rememberLogin') === 'true'
      
      if (rememberedUsername && rememberLogin) {
        // 这里可以实现使用记住的凭据自动登录
        // 但出于安全考虑，通常不会保存密码
        console.log('检测到记住的用户名，但需要用户重新输入密码')
      }

      return false
    } catch (error) {
      console.error('自动重新登录失败:', error)
      return false
    }
  }
  
  // 确保token有效
  const ensureValidToken = async () => {
    if (!accessToken.value) {
      return null
    }
    
    // 如果token已过期，尝试刷新
    if (isTokenExpired.value) {
      try {
        return await refreshAccessToken()
      } catch (error) {
        return null
      }
    }
    
    // 如果token即将过期（5分钟内），提前刷新
    if (isTokenExpiringSoon.value) {
      try {
        return await refreshAccessToken()
      } catch (error) {
        // 刷新失败，但当前token仍然有效，继续使用
        console.warn('提前刷新token失败，继续使用当前token:', error)
        return accessToken.value
      }
    }
    
    return accessToken.value
  }
  
  return {
    // 状态
    accessToken,
    refreshToken,
    userInfo,
    tokenExpiresAt,
    
    // 计算属性
    isTokenExpired,
    isTokenExpiringSoon,
    isLoggedIn,
    
    // 方法
    setAuthData,
    setToken, // 兼容性方法
    logout,
    refreshAccessToken,
    ensureValidToken,
    autoRelogin
  }
})