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

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const isLoggedIn = computed(() => !!token.value)

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  // 登录
  const login = (tokenValue, name, userLevel, department, departmentId) => {
    setToken(tokenValue)
    const userInfoData = {
      username: name,
      user_level: userLevel,
      department: department,
      department_id: departmentId
    }
    setUserInfo(userInfoData)
  }

  // 登出
  const logout = () => {
    setToken('')
    setUserInfo(null)
    localStorage.removeItem('token')
    sessionStorage.removeItem('token')
  }

  // 清除所有数据
  const clearAll = () => {
    logout()
  }

  return {
    // 状态
    token,
    userInfo,
    isLoggedIn,
    
    // 方法
    setToken,
    setUserInfo,
    login,
    logout,
    clearAll
  }
}, {
  // 持久化配置（可选）
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token', 'userInfo']
  }
})