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

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  
  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => userInfo.value.role === 'admin')
  
  function setToken(newToken) {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }
  
  function setUserInfo(info) {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  
  function updateUserAvatar(avatarUrl) {
    userInfo.value.avatar = avatarUrl
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }
  
  // 登录方法
  const login = async (credentials) => {
    try {
      // 这里应该调用实际的登录 API
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials)
      })
      const data = await response.json()
      
      token.value = data.token
      userInfo.value = data.user
      
      localStorage.setItem('token', data.token)
      localStorage.setItem('userInfo', JSON.stringify(data.user))
    } catch (error) {
      console.error('Login failed:', error)
      throw error
    }
  }
  
  // 登出方法
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  
  // 初始化时从本地存储加载数据
  function init() {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    if (storedToken) {
      token.value = storedToken
    }
    
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
      } catch (e) {
        console.error('Failed to parse stored user info:', e)
      }
    }
  }
  
  // 添加一个模拟登录的方法
  const mockAdminLogin = () => {
    const adminData = {
      id: 1,
      username: 'admin',
      name: '管理员',
      role: 'admin',
      avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      email: 'admin@example.com'
    }
    
    token.value = 'mock-admin-token'
    userInfo.value = adminData
    
    // 保存到本地存储
    localStorage.setItem('token', token.value)
    localStorage.setItem('userInfo', JSON.stringify(adminData))
  }
  
  // 初始化
  init()
  
  return {
    token,
    userInfo,
    isLoggedIn,
    isAdmin,
    setToken,
    setUserInfo,
    updateUserAvatar,
    login,
    logout,
    init,
    mockAdminLogin  // 导出模拟登录方法
  }
}) 