import { defineStore } from 'pinia'
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 defAva from '@/assets/images/defAva.png'
import { Login } from '@/api/interface/index'
export const useUserStore = defineStore('admin-user', {
  state: (): UserState => ({
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  }),
  getters: {},
  actions: {
    userLogin(userInfo: Login.ReqLoginForm) {
      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 avatar = user.avatar == '' || user.avatar == null ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar
              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 = avatar
            }
            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')
})
