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

// 平台登录缓存仅保留以下字段（不含 tid、group_id）
const defaultUser = {
  id: '',
  account: '',
  name: '',
  rid: '',
  avatar: '',
  role_name: ''
}

/**
 * 规范化写入 localStorage 的用户信息，去掉 tid、group_id 等废弃字段；
 * 若仅有历史 group_id，则迁移到 rid。
 */
function normalizePlatformUser(raw) {
  if (!raw || typeof raw !== 'object') {
    return { ...defaultUser }
  }
  let rid = raw.rid
  if (rid === undefined || rid === null || rid === '') {
    const legacy = raw.group_id
    if (legacy !== undefined && legacy !== null && legacy !== '') {
      rid = legacy
    }
  }
  return {
    id: parseInt(raw.id, 10) || null,
    account: raw.account || '',
    name: raw.name || '',
    rid: rid !== undefined && rid !== null && rid !== '' ? rid : '',
    avatar: raw.avatar || '',
    role_name: raw.role_name || ''
  }
}

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 parsed = JSON.parse(cachedUser)
        const normalized = normalizePlatformUser(parsed)
        Object.assign(user, normalized)
        localStorage.setItem('userInfo', JSON.stringify(normalized))
      } catch (e) {
        console.error('Failed to parse user info from cache:', e)
      }
    }
  }

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

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

    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(partial) {
    const merged = normalizePlatformUser({ ...user, ...partial })
    Object.assign(user, merged)
    localStorage.setItem('userInfo', JSON.stringify(merged))
  }

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