import { defineStore } from 'pinia'
import { getToken,setToken,removeToken } from '@/utils/auth.js'

export const useAuthStore = defineStore('auth', {
	state: () => ({
		token: null,
		tokenExp:null,
		userInfo: null,
		phone: null,
		creditCard: '',
		openid: null,
	}),
	actions: {
		setCreditCard(creditCard) {
			this.creditCard = creditCard
		},
		setAuthToken(newToken, newTokenExp) {
			this.token = newToken
			this.tokenExp = newTokenExp
			uni.setStorageSync('tokenExp', newTokenExp)
			// 可以选择将 token 存储到 localStorage 或 sessionStorage
			setToken(newToken)
		},
		clearAuthToken() {
			this.token = null
			this.tokenExp = null
			uni.removeStorageSync("tokenExp")
			removeToken()
		},
		loadAuthToken() {
			const savedToken = getToken()
			if (savedToken) {
				this.token = savedToken
				this.tokenExp = uni.getStorageSync('tokenExp') || null
			}
		},
		setUserInfo(data) {
		  this.userInfo = data
		  uni.setStorageSync('USER_INFO', data)
		},
		setUserIcon(data) {
			this.userInfo.userIcon = data
		    uni.setStorageSync('USER_INFO', this.userInfo)
		},
		// 初始化时从Storage加载
		loadUserInfo() {
		  this.userInfo = uni.getStorageSync('USER_INFO') || null
		},
		cleanUserInfo() {
			this.userInfo = null
			uni.removeStorageSync("USER_INFO")
		},
		setPhone(data) {
		  this.phone = data
		  uni.setStorageSync('phone', data)
		},
		// 初始化时从Storage加载
		loadPhone() {
		  this.phone = uni.getStorageSync('phone') || null
		},
		cleanPhone() {
			this.phone = null
			uni.removeStorageSync("phone")
		},
		setOpenid(data) {
		  this.openid = data
		  uni.setStorageSync('openid', data)
		},
		// 初始化时从Storage加载
		loadOpenid() {
		  this.openid = uni.getStorageSync('openid') || null
		},
		cleanOpenid() {
			this.openid = null
			uni.removeStorageSync("openid")
		},
	},
	getters: {
		isAuthenticated(state) {
			return !!state.token; // 如果 token 存在，返回 true；否则返回 false
		},
		isUserInfo(state){
			return !!state.userInfo;
		},
		isOpenid(state){
			return !!state.openid;
		},
		isTokenExp(state){
			const now = Date.now();
			return !this.tokenExp || now > this.tokenExp;
		}
	}
})