// 每一个存储的模块，命名规则use开头，store结尾
import { AccountLogout } from '@/api/account'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { removeLocal, setLocal } from '@/utils/local'
import MyEvent from '@/utils/myEvent'
import router from '@/router'
export const useUserInfoStore = defineStore('userInfo', () => {
	const state = ref({
		userInfo: {
			userId: "",
			email: "",
			username: "",
			accessToken: "",
			expiresIn: "",
		},
		token: ''
	})

	// actions
	const setUserInfo = (data: any) => {
		state.value.userInfo = data
		setToken(data.accessToken)
	}

	const setToken = (data: string) => {
		state.value.token = data
		setLocal(data, 'token')
	}

	const logout = async (reload: boolean = false) => {
		// 处理退出登录的一些逻辑
		const userId = state.value.userInfo.userId
		if (userId) await AccountLogout({ userId })
		state.value.userInfo = {
			userId: "",
			email: "",
			username: "",
			accessToken: "",
			expiresIn: "",
		}
		state.value.token = ''
		removeLocal('token')
		if (reload) router.go(0)

	}

	return {
		state,
		setToken,
		setUserInfo,
		logout
	}
})
