import { reactive } from "vue"
import service from '@/service'
import request from '@/utils/request'
import { setToken, removeToken } from '@/utils/token'
import { replacePathParam } from '@/utils'

export default () => {
  const user = reactive({})

  const setUser = o => Object.keys(o).forEach(k => (user[k] = o[k]))

  const getCurrent = () => {
    return request(replacePathParam(service.user.detail, {id: 'current'})).then(data => {
      setUser(data)
      return user
    })
  }

  const getUser = (id) => {
    return request(replacePathParam(service.user.detail, {id})).then(data => {
      return data
    })
  }

  const login = data => {
    return request({
      ...service.user.login,
      data,
    }).then(res => {
      setUser(res)
      setToken(res.token)
      return user
    })
  }

  const logout = () => {
    return request(service.user.logout).then(res => {
      return removeToken()
    })
  }

  const saveUser = data => {
    return request({
      ...service.user.save,
      data,
    }).then(res => {
      return res
    })
  }

  const updateUser = data => {
    const params = {
      ...service.user.update,
      data,
    }

    return request(replacePathParam(params, {id: data.userId})).then(res => {
      return res
    })
  }

  return {
    user,
    getUser,
    getCurrent,
    setUser,
    login,
    logout,
    saveUser,
    updateUser,
  }
}
