import { defineStore } from 'pinia'
import { ref } from 'vue'
import { coinLoginApi, UserT } from '@/service/index/foo'
import type { IUserInfo } from '@/typings'

const initState = {
  nickname: '',
  avatar: '',
  openid: '',
  coin_address: '',
  scene: '',
  terminal: '',
  share_code: '',
  firstName: '',
  id: '',
  languageCode: '',
  lastName: '',
  username: '',
  token: '',
}

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

    const setUserInfo = async (val: IUserInfo, shareCode: string) => {
      val.age_limit = uni.getStorageSync('age') || ''
      userInfo.value = val
      userInfo.value.share_code = shareCode
      const { data } = await coinLoginApi(val)
      userInfo.value.token = data.tokenValue
      uni.setStorageSync('token', data.tokenValue)
      return new Promise<UserT>((resolve) => {
        resolve(data)
      })
    }
    const shareCode = ref(uni.getStorageSync('shareCode') || '')
    const setShareCode = (val: string) => {
      shareCode.value = val
    }
    // 清除用户信息
    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }
    const isLogined = computed(() => !!userInfo.value.token)

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