import { defineStore } from 'pinia'
import { getUser } from '@/api/login/index.js'

export const useUserStore = defineStore('user', {
  persist: {
    enabled: true
  },
  state() {
    return {
      userInfo: {
        hasLogin: false
      }
    }
  },
  getters: {
    // userId() {
    //   return this.userInfo?.id
    // },
    userName() {
      return this.userInfo?.userName
    },
    realname() {
      return this.userInfo?.realname
    },
    avatar() {
      return this.userInfo?.avatar
    },
    role() {
      return this.userInfo?.role || []
    },
    authority() {
      return this.userInfo.authority
    },
    hasLogin() {
      return this.userInfo.hasLogin
    }
  },
  actions: {
    async getUserInfos() {
      try {
        const res = await getUser()
        if (res.code === 0) {
          this.setUserInfo({ hasLogin: true, ...res.data })
          return Promise.resolve(res.data.type)
        } else {
          this.setUserInfo()
        }
      } catch (error) {
        console.error(error)
        this.setUserInfo()
      }
    },
    setUserInfo(userInfo = { hasLogin: false }) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    }
  }
})
