import { type UserState } from '@/stores/interface'
import { getToken, setToken, removeToken } from '@/utils/token'
import { type LoginData } from '@/api/interface/login'
import UserApi from '@/api/module/system/user'
import { type UserInfo } from '@/api/interface/system/user'
import LoginApi from '@/api/module/login'
import { pinia } from '../index'

export const useUserStore = defineStore('eco-user', {
  state: (): UserState => ({
    token: getToken(),
    name: '',
    avatar: '',
    nickname: '',
    userId: '',
    tenantId: '',
    roles: [],
    permissions: []
  }),
  getters: {},
  actions: {
    userLogin(loginData: LoginData) {
      return new Promise<Result>((resolve, reject) => {
        LoginApi.login(loginData)
          .then(({ code, data, msg }) => {
            if (code === 200) {
              const { tokenType, accessToken } = data
              setToken(tokenType + ' ' + accessToken)
              this.token = tokenType + ' ' + accessToken
              resolve({ code, msg })
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    userLogout() {
      return new Promise<Result>((resolve, reject) => {
        LoginApi.logout()
          .then(({ code, msg }) => {
            if (code === 200) {
              this.token = ''
              this.roles = []
              this.permissions = []
              removeToken()
              resolve({ code, msg })
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    getUserInfo() {
      return new Promise<UserInfo>((resolve, reject) => {
        UserApi.getInfo()
          .then(({ code, data }) => {
            if (code === 200) {
              const { user, roles, permissions } = data
              this.avatar = user.avatar
              this.roles = roles
              this.name = user.userName
              this.permissions = permissions
              resolve(data)
            } else {
              this.roles = []
              removeToken()
            }
          })
          .catch(error => {
            this.roles = []
            removeToken()
            reject(error)
          })
      })
    },
    setToken(tokenStr: string) {
      this.token = tokenStr
    }
  }
})
export const useUserStoreWithOut = () => {
  return useUserStore(pinia)
}
