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

// 用户信息类型
const defaultUser = {
  id:'',
  account: '',
  name: '',
  group_id: '',
  type: 'backend',
  avatar: ''
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const isLoggedIn = ref(!!token.value)
  const user = reactive({ ...defaultUser })

  // 从缓存加载用户信息
  function loadUserFromCache() {
    const cachedUser = localStorage.getItem('userInfo')
    if (cachedUser) {
      try {
        const userInfo = JSON.parse(cachedUser)
        Object.assign(user, userInfo)
      } catch (e) {
        console.error('Failed to parse user info from cache:', e)
      }
    }
  }

  // 初始化时加载用户信息
  loadUserFromCache()

  // 保存登录信息（token 和用户信息）
  function setLoginInfo(loginData) {
    const userInfo = loginData.user || loginData

    const normalizedUser = {
      id: parseInt(userInfo.id) || null,
      account: userInfo.account || '',
      name: userInfo.name || '',
      group_id: userInfo.group_id || '',
      type: 'backend',
      tid: userInfo.tid || '',
      avatar: userInfo.avatar || ''
    }

    // 使用后端返回的真实 JWT token
    const accessToken = loginData.token || ''

    token.value = accessToken
    isLoggedIn.value = !!accessToken
    localStorage.setItem('token', accessToken)

    Object.assign(user, normalizedUser)
    localStorage.setItem('userInfo', JSON.stringify(normalizedUser))
  }

  // 设置 token（兼容旧代码）
  function setToken(newToken) {
    token.value = newToken
    isLoggedIn.value = true
    localStorage.setItem('token', newToken)
  }

  // 清除登录信息
  function clearToken() {
    token.value = ''
    isLoggedIn.value = false
    Object.assign(user, defaultUser)
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 检查认证状态
  function checkAuth() {
    const storedToken = localStorage.getItem('token')
    if (storedToken) {
      token.value = storedToken
      isLoggedIn.value = true
      loadUserFromCache()
    } else {
      token.value = ''
      isLoggedIn.value = false
      Object.assign(user, defaultUser)
    }
  }

  // 更新用户信息
  function updateUserInfo(userInfo) {
    Object.assign(user, userInfo)
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  }

  return {
    token,
    isLoggedIn,
    user,
    setLoginInfo,
    setToken,
    clearToken,
    checkAuth,
    updateUserInfo
  }
})

