import { defineStore } from 'pinia'
import { resetRouter } from '@/router'
import { useTagsStore, usePermissionStore } from '@/store'
import { removeToken, toLogin } from '@/utils'
import api from '@/api/user'

export const useUserStore = defineStore('user', {
  state() {
    return {
      userInfo: {
        id: '',
        account: '',
        nickname: '',
        avatar: '',
        contact: '',
        isAdmin: 0,
        status: 1
      },
    }
  },
  getters: {
    id() {
      return this.userInfo?.id
    },
    account() {
      return this.userInfo?.account
    },
    nickname() {
      return this.userInfo?.nickname
    },
    avatar() {
      return this.userInfo?.avatar
    },
    contact() {
      return this.userInfo?.contact
    },
    isAdmin() {
      return this.userInfo?.isAdmin
    },
    status() {
      return this.userInfo?.status
    },
    localUserInfo() {
      return this.userInfo
    }
  },
  actions: {
    async getUserInfo() {
      try {
        const res = await api.getUser()
        const { id, account,nickname, avatar,contact,isAdmin,status } = res.data.data
        this.userInfo = { id, account,nickname, avatar, contact,isAdmin,status }
        return Promise.resolve(res.data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async logout() {
      const { resetTags } = useTagsStore()
      const { resetPermission } = usePermissionStore()
      removeToken()
      resetTags()
      resetPermission()
      resetRouter()
      this.$reset()
      toLogin()
    },
    setUserInfo(userInfo = {}) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    },
  },
})
