import { defineStore } from 'pinia'
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { auth } from '../utils/api'
import { authUtils } from '../utils/auth'
import { http } from '../utils/http'
import router from '../router'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref(null)
  const token = ref('')
  
  // 初始化时从加密存储中获取数据
  try {
    const encryptedUser = localStorage.getItem('user')
    const encryptedToken = localStorage.getItem('token')
    if (encryptedUser) {
      user.value = authUtils.decrypt(encryptedUser)
    }
    if (encryptedToken) {
      token.value = authUtils.decrypt(encryptedToken)
    }
  } catch (error) {
    console.error('Failed to load auth state:', error)
    clearAuth()
  }

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)

  // 监听存储变化，实现多标签页同步
  function handleStorageChange(event) {
    if (event.key === 'auth_sync') {
      try {
        const { type, data } = JSON.parse(event.newValue)
        switch (type) {
          case 'logout':
            clearAuth()
            router.push('/login')
            break
          case 'token_refreshed':
            if (data?.access_token) {
              token.value = data.access_token
            }
            break
          case 'user_updated':
            if (data?.user) {
              user.value = data.user
            }
            break
        }
      } catch (error) {
        console.error('Failed to handle auth sync:', error)
      }
    }
  }

  // 设置监听器
  onMounted(() => {
    window.addEventListener('storage', handleStorageChange)
  })

  // 清理监听器
  onUnmounted(() => {
    window.removeEventListener('storage', handleStorageChange)
  })

  // 方法
  function setAuth(data) {
    if (!data || !data.access_token) return false
    
    // 加密存储token和refresh token
    token.value = data.access_token
    localStorage.setItem('token', authUtils.encrypt(data.access_token))
    if (data.refresh_token) {
      localStorage.setItem('refreshToken', authUtils.encrypt(data.refresh_token))
    }
    
    // 获取用户信息
    getCurrentUser()
    
    return true
  }

  function clearAuth() {
    user.value = null
    token.value = null
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    authUtils.broadcastAuthChange('logout')
  }

  async function getCurrentUser() {
    try {
      const response = await auth.getCurrentUser()
      if (response.data) {
        user.value = response.data
        // 加密存储用户信息
        localStorage.setItem('user', authUtils.encrypt(response.data))
        authUtils.broadcastAuthChange('user_updated', { user: response.data })
        return true
      }
      return false
    } catch (error) {
      console.error('Get current user error:', error)
      clearAuth()
      return false
    }
  }

  async function login(credentials) {
    try {
      const response = await auth.login(credentials)
      if (response.data && response.data.access_token) {
        const success = setAuth(response.data)
        if (success) {
          return { success: true }
        }
      }
      
      return {
        success: false,
        error: '登录失败：服务器返回的数据无效'
      }
    } catch (error) {
      console.error('Login error:', error)
      return {
        success: false,
        error: error.response?.data?.message || '登录失败，请稍后重试'
      }
    }
  }

  async function register(userData) {
    try {
      const response = await auth.register(userData)
      return { success: true }
    } catch (error) {
      console.error('Register error:', error)
      return {
        success: false,
        error: error.response?.data?.message || '注册失败，请稍后重试'
      }
    }
  }

  async function refreshToken() {
    try {
      const refreshToken = authUtils.decrypt(localStorage.getItem('refreshToken'))
      if (!refreshToken) {
        throw new Error('No refresh token available')
      }

      const response = await http.post('/api/v1/auth/refresh', { refresh_token: refreshToken })
      if (response.data?.access_token) {
        const success = setAuth(response.data)
        if (success) {
          return { success: true }
        }
      }
      throw new Error('Token refresh failed')
    } catch (error) {
      console.error('Token refresh failed:', error)
      clearAuth()
      throw error
    }
  }

  function logout() {
    clearAuth()
    router.push('/login')
  }

  // 检查认证状态
  function checkAuth() {
    const encryptedToken = localStorage.getItem('token')
    if (encryptedToken) {
      const decryptedToken = authUtils.decrypt(encryptedToken)
      if (decryptedToken) {
        // 检查token是否接近过期
        if (authUtils.isTokenNearExpiry(decryptedToken)) {
          // 触发token刷新
          refreshToken().catch(() => {
            clearAuth()
            router.push('/login')
          })
        }
        token.value = decryptedToken
        return true
      }
    }
    return false
  }

  // 初始化时检查认证状态
  checkAuth()

  return {
    user,
    token,
    isAuthenticated,
    login,
    logout,
    register,
    getCurrentUser,
    refreshToken,
    checkAuth
  }
})
