import { defineStore } from 'pinia'
import axios from 'axios'

export const useUserStore = defineStore('user', {
  state: () => ({
    userId: 10, // 默认用户 ID
    username: '', // 新增：用户名
  }),
  getters: {
    getUserId: (state) => state.userId,
    getUsername: (state) => state.username, // 新增 getter
  },
  actions: {
    setUserId(id: number) {
      this.userId = id
    },
    setUsername(name: string) {
      this.username = name
    },
    async fetchUsernameById(id: number) {
      try {
        // 设置 userId
        this.userId = id

        const response = await axios.get(`/api/user/customers/${id}`)//ok

        // 后端返回的用户数据结构中包含 accountName
        this.username = response.data.accountName
      } catch (error) {
        console.error('获取用户名失败:', error)
      }
    },
  },
})
