import type { loginResult, token } from '@/types/member'
import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义 Store
export const useMemberStore = defineStore(
  'member',
  () => {
    // 会员信息
    const profile = ref<loginResult>()

    // 保存会员信息，登录时使用
    const setProfile = (val: loginResult) => {
      profile.value = { ...profile.value, ...val }
      profile.value.mobile = profile.value.mobile.replace(/(\d{3})\d{4}(\d{3})/, '$1****$2')
    }

    // 清理会员信息，退出时使用
    const clearProfile = () => {
      profile.value = undefined
    }

    // 更新token
    const updateToken = (token: token) => {
      profile.value!.token = token.token
    }

    return {
      profile,
      setProfile,
      clearProfile,
      updateToken,
    }
  },
  {
    persist: {
      storage: {
        setItem(key: string, value: any) {
          uni.setStorageSync(key, value)
        },
        getItem(key: string) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
