import { getRealNameAuthAPI, getUserInfoAPI, logoutUserAPI } from '@/service'
import { mergeStep } from '@/utils'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo | null>(null)
    const token = ref('')

    const loadUserInfo = mergeStep(async () => {
      const res = await getUserInfoAPI()
      userInfo.value = res.data.userinfo

      getRealNameAuthAPI().then((res) => {
        if (Number(res.data?.status) !== 2) {
          uni.reLaunch({
            url: '/pages-sub/realname/index',
          })
        }
        userInfo.value.realname = res.data?.realname
        return res.data
      })
    })

    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }
    const setToken = (val: string) => {
      token.value = val
    }

    const clearUserInfo = () => {
      userInfo.value = null
    }
    const clearToken = () => {
      token.value = ''
    }
    const logout = async () => {
      // logoutUserAPI()
      clearUserInfo()
      clearToken()
    }

    const isLogged = computed(() => !!token.value)

    return {
      userInfo,
      loadUserInfo,
      setUserInfo,
      clearUserInfo,
      isLogged,
      setToken,
      token,
      logout,
    }
  },
  {
    persist: true,
  },
)
