import { userInfo } from '@/api/login'
import { defineStore } from 'pinia'
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: () : UserInfosStates => ({
		userInfos: uni.getStorageSync('userInfo'),
		token: uni.getStorageSync('token'),
	}),
	actions: {
		async getUserInfo() {
			const res = await userInfo({})
			const data = res.data
			this.setUserInfos(data)
			return data
		},
		setUserInfos(userInfos) {
			// 存储用户信息到浏览器缓存
			uni.setStorageSync('userInfo', userInfos)
			this.userInfos = userInfos
		},
		setToken(token : string) {
			// 存储用户信息到浏览器缓存
			uni.setStorageSync('token', token)
			// 更新 store 状态
			this.token = token
			// 获取用户信息
			this.getUserInfo()
		},
		logout() {
			uni.clearStorageSync()
			this.userInfos = '';
			this.token = '';
			uni.redirectTo({
				url: "/pages/login/index"
			})
		},
	},
})