import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(uni.getStorageSync('token') || '')
  const userInfo = ref<any>(uni.getStorageSync('userInfo') || null)
  const isAgent = ref<boolean>(false)

  // 计算属性：是否已登录
  const isLoggedIn = computed(() => !!token.value)

  // 设置token
  function setToken(newToken: string) {
    token.value = newToken
    uni.setStorageSync('token', newToken)
  }

  // 设置用户信息
  function setUserInfo(info: any) {
    userInfo.value = info
    isAgent.value = info?.role === 'agent'
    uni.setStorageSync('userInfo', info)
  }

  // 登出
  function logout() {
    token.value = ''
    userInfo.value = null
    isAgent.value = false
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
  }

  return {
    token,
    userInfo,
    isAgent,
    isLoggedIn,
    setToken,
    setUserInfo,
    logout
  }
})
