import { reactive } from 'vue'
import { login as loginApi, logout as logoutApi, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resolveResourceUrl } from '@/utils/resourceUrl'

const state = reactive({
  token: getToken(),
  id: '',
  name: '',
  nickName: '',
  avatar: '',
  roles: [],
  permissions: []
})

function resolveAvatar(path) {
  return resolveResourceUrl(path)
}

export function useUserStore() {
  const login = (userInfo) => {
    const username = (userInfo.username || '').trim()
    const password = userInfo.password
    const code = userInfo.code
    const uuid = userInfo.uuid
    return loginApi(username, password, code, uuid).then((res) => {
      const token = res.token
      setToken(token)
      state.token = token
      return res
    })
  }

  const fetchUserInfo = () => {
    return getInfo().then((res) => {
      const user = res.user || {}
      if (res.roles && res.roles.length > 0) {
        state.roles = res.roles
        state.permissions = res.permissions || []
      } else {
        state.roles = ['ROLE_DEFAULT']
        state.permissions = []
      }
      state.id = user.userId
      state.name = user.userName
      state.nickName = user.nickName
      state.avatar = resolveAvatar(user.avatar)
      return res
    })
  }

  const logOut = () => {
    return logoutApi()
      .catch(() => {})
      .finally(() => {
        state.token = ''
        state.roles = []
        state.permissions = []
        state.id = ''
        state.name = ''
        state.nickName = ''
        state.avatar = ''
        removeToken()
      })
  }

  const fedLogOut = () => {
    state.token = ''
    state.roles = []
    state.permissions = []
    state.id = ''
    state.name = ''
    state.nickName = ''
    state.avatar = ''
    removeToken()
    return Promise.resolve()
  }

  const displayName = () => {
    return state.nickName || state.name || ''
  }

  const isLoggedIn = () => !!state.token

  return {
    state,
    login,
    fetchUserInfo,
    logOut,
    fedLogOut,
    displayName,
    isLoggedIn
  }
}
