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

export interface UserInfo {
  id: number
  username: string
  nickname: string
  avatar: string
  phone: string
  companyName: string
  deptName: string
  role: string
}

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)

  const isLoggedIn = computed(() => !!token.value)

  // 模拟用户信息
  const mockUserInfo: UserInfo = {
    id: 1,
    username: 'admin',
    nickname: '张三',
    avatar: '',
    phone: '138****8888',
    companyName: '优易科技有限公司',
    deptName: '采购部',
    role: '采购负责人'
  }

  // 登录
  const login = async (username: string, password: string) => {
    // TODO: 调用登录接口
    token.value = 'mock_token_' + Date.now()
    localStorage.setItem('token', token.value)
    userInfo.value = mockUserInfo
    return true
  }

  // 获取用户信息
  const getUserInfo = async () => {
    if (!token.value) return null
    // TODO: 调用获取用户信息接口
    userInfo.value = mockUserInfo
    return userInfo.value
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    getUserInfo,
    logout
  }
})
