import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { useAppStore } from './app'
import { login } from '@/api/user'

interface UserState {
  token: string
  name: string
  avatar: string
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: getToken(),
    name: '',
    avatar: 'user-avatar.gif'
  }),
  
  actions: {
    // 用户登录
    async login(userInfo: {username: string, password: string}) {
      const { username, password } = userInfo
      try {
        const res = await login({
          username: username.trim(),
          password: password
        })
        
        if (res.code === 0) {
          const token = res.data.token
          this.token = token
          setToken(token)
          return Promise.resolve()
        } else {
          return Promise.reject(res.message)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getInfo() {
      // 这里保留了 getInfo 方法，后续会根据实际需求修改
      this.name = 'Admin'
      this.avatar = 'user-avatar.gif'
      return {
        name: this.name,
        avatar: this.avatar,
        roles: ['admin']
      }
    },
    
    // 用户登出
    async logout() {
      this.token = ''
      this.name = ''
      removeToken()
      resetRouter()
    },
    
    // 重置令牌
    resetToken() {
      this.token = ''
      removeToken()
    },
    
    // 侧边栏相关
    toggleSidebar() {
      const appStore = useAppStore()
      appStore.toggleSidebar()
    }
  }
})
