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

	})

	const getUserInfo = async () => {
		const res = await GetUserInfo()
		if (res) {
			state.value.userInfo = { ...res }
		} else {
			state.value.userInfo = {}
		}
	}

	const updateUserInfo = (data: any) => {
		state.value.userInfo = { ...state.value.userInfo, ...data }
	}

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

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

	const logOut = async (isApi: boolean = true) => {
		// 处理退出登录的一些逻辑
		if (isApi) await Logout()
		state.value.token = ''
		state.value.userInfo = {}
		// removeLocal('token')
		// MyEvent.emit('clear-generate-state')
		// MyEvent.emit('clear-client-state')
		// MyEvent.emit('clearAllCache')
		router.push({ name: 'login' })
		return ""
	}

	return {
		state,
		getUserInfo,
		setToken,
		setUserInfo,
		logOut,
		updateUserInfo
	}
})
