import {defineStore} from "pinia";
import type User from "@/mode/User";
import type Details from '@/mode/Details'
import type UserSimple from "@/mode/UserSimple";
import UserApi from "@/api/UserApi";

export interface State {
	user: User | null;
	userMap: Map<string, UserSimple>;
	details:Details| null
}

// defineStore 调用后返回一个函数，调用该函数获得 Store 实体
export const useUserStore = defineStore({
	// id: 必须的，在所有 Store 中唯一
	id: "user_store",
	// state: 返回对象的函数
	state: (): State => ({
		user: null,
		userMap: new Map<string, UserSimple>(),
		details:null
	}),
	// 开启数据缓存
	persist: {
		enabled: true,
		strategies: [
			{
				key: 'user',
				storage: localStorage,
				paths: ['user']
			}
		]
	},
	getters: {
		getMapUser: (state) => {
			return (id: string) => {
				return state.userMap.get(id)
			}
		}
	},
	actions: {
		setUser(user: User): void {
			this.user = user;
		},
		getUser(): User | null {
			return this.user;
		},
		setDetails(details: Details): void {
		  this.details = details
		},
		getDetails(): Details | null {
		  return this.details
		},
		getCacheUser(userId:string): UserSimple | undefined {
			return this.userMap?this.userMap.get(userId):undefined;
		},
		storeUser(userId: string,user: UserSimple): void {
			 this.userMap.set(userId,user);
		},
		async loadMapUser(id: string) {
			return UserApi.getUser(id).then((res) => {
				if (res.data) {
					this.storeUser(id, res.data)
				}
			})
		}
	},
});
