import { defineStore } from 'pinia';

export const useUserStore = defineStore('storeUser', {
    state: () => {
        return {
            id: '',
            username: '',
            token: '',
            loginUser: null,
            userType: '',
            roleId: '',
            permissions: [] as string[],  // 权限列表
            roles: [] as string[],         // 角色列表
        };
    },
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'userStore',
                storage: localStorage,
            },
        ],
    },
    getters: {
        // 判断是否有某个权限
        hasPermission: (state) => {
            return (permission: string) => {
                if (state.permissions.includes('*:*:*')) {
                    return true;
                }
                return state.permissions.includes(permission);
            };
        },
        // 判断是否有某个角色
        hasRole: (state) => {
            return (role: string) => {
                if (state.roles.includes('admin')) {
                    return true;
                }
                return state.roles.includes(role);
            };
        },
    },
    actions: {
        removeAllInfo() {
            this.id = '';
            this.username = '';
            this.token = '';
            this.userType = '';
            this.loginUser = null;
            this.userType = ''
            this.roleId = ''
            this.permissions = [];  // 清空权限
            this.roles = [];        // 清空角色
        },
        updateToken(token: string) {
            this.token = token;
        },
        updateUserType(userType: string) {
        this.userType = userType;
        },
        updateUserName(userName: string) {
            this.username = userName;
        },
        updateLoginUser(user: Object) {
            // @ts-ignore
            this.loginUser = user;
        },
        updateLoginUserType(userType: number) {
            // @ts-ignore
            this.userType = userType;
        },
        updateRoleId(roleId: string) {
            this.roleId = roleId
        },
        // 更新权限列表
        updatePermissions(permissions: string[]) {
            this.permissions = permissions || [];
        },
        // 更新角色列表
        updateRoles(roles: string[]) {
            this.roles = roles || [];
        },
    },
});
