import { UserState } from '@/stores/interface'
import piniaPersistConfig from '@/stores/helper/persist'
import { getToken, setToken, removeToken } from '@/utils/token'
import { loginApi, getInfoApi, logoutApi } from '@/api/modules/login'
import defAvatar from '@/assets/images/avatar.jpg'
import { LoginData } from '@/api/interface/login'
export const useUserStore = defineStore('admin-user', {
  state: (): UserState => ({
    token: getToken(),
    name: '',
    avatar: '',
    nickname: '',
    userId: '',
    tenantId: '',
    roles: [],
    permissions: []
  }),
  getters: {},
  actions: {
    userLogin(userInfo: LoginData) {
      return new Promise<any>((resolve, reject) => {
        loginApi(userInfo)
          .then((res: any) => {
            if (res.code === 200) {
              const data = res.data
              setToken(data.access_token)
              this.token = data.access_token
              resolve(res)
            } else resolve({ code: 500 })
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfoApi()
          .then((res: any) => {
            if (res.code === 200) {
              const data = res.data
              const user = data.user
              const profile = user.url == '' || user.url == null ? defAvatar : user.url
              if (data.roles && data.roles.length > 0) {
                // 验证返回的roles是否是一个非空数组
                this.roles = data.roles
                this.permissions = data.permissions
              } else {
                this.roles = ['ROLE_DEFAULT']
              }
              this.name = user.userName
              this.avatar = profile
              this.nickname = user.nickName
              this.userId = user.userId
              this.tenantId = user.tenantId
            }
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logoutApi()
          .then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve(1)
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  },
  persist: piniaPersistConfig('admin-token')
})
