import { getUserInfoAPI, updateUserInfoAPI } from '@/service/login'
import { UpdateUserInfoRequest } from '@/service/login/type'
import { defineStore } from 'pinia'
import { ref } from 'vue'

const initState = { nickname: '', avatar: '' }

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState })

    const setUserInfo = async () => {
      const ID = uni.getStorageSync('loginData')?.ID || ''
    }

    const updateUserInfo = async (data: UpdateUserInfoRequest) => {
      const res = await updateUserInfoAPI({ ...data, id: uni.getStorageSync('loginData')?.id })
      return res
    }

    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }
    const isLogined = computed(() => !!userInfo.value['x-token'])

    return {
      userInfo,
      setUserInfo,
      updateUserInfo,
      clearUserInfo,
      isLogined,
      reset,
    }
  },
  {
    persist: true,
  },
)
