package com.njzscloud.common.security.support;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.njzscloud.common.core.fastjson.serializer.DictObjectDeserializer;
import com.njzscloud.common.core.fastjson.serializer.DictObjectSerializer;
import com.njzscloud.common.security.contant.AuthWay;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.security.core.CredentialsContainer;

import java.security.Principal;
import java.util.Set;

import static com.njzscloud.common.security.contant.Constants.ROLE_ANONYMOUS;

/**
 * 用户信息
 */
@Getter
@Setter
@Accessors(chain = true)
public class UserDetail implements CredentialsContainer, Principal {

    /**
     * 用户 Id
     */
    private Long userId;
    /**
     * 昵称
     */
    private String nickname;
    /**
     * 密码
     */
    @JsonIgnore
    private String secret;
    /**
     * 账号 Id
     */
    private Long accountId;
    /**
     * 允许的客户端
     */
    private Integer clientCode;
    /**
     * 当前客户端
     */
    private Integer client;

    private Long tenantId;
    private String tenantName;
    /**
     * 登录方式
     */
    @JSONField(serializeUsing = DictObjectSerializer.class, deserializeUsing = DictObjectDeserializer.class)
    private AuthWay authWay;
    /**
     * 角色编码
     */
    private Set<String> roles;
    @JsonSerialize(using = TokenSerializer.class)
    private Token token;
    /**
     * 是否禁用; 0-->启用、1-->禁用
     */
    private Boolean disabled;

    public static UserDetail anonymousUser() {
        return new UserDetail()
            .setUserId(0L)
            .setAccountId(0L)
            .setRoles(CollUtil.newHashSet(ROLE_ANONYMOUS))
            .setToken(Token.anonymousToken());
    }

    /**
     * 账号是否过期
     */
    // private boolean accountExpired = false;

    /**
     * 账号是否被锁定
     */
    // private boolean accountLocked = false;

    /**
     * 密码是否过期
     */
    // private boolean credentialsExpired = false;

    /**
     * 是否启用
     */
    // private boolean disable = false;
    @Override
    @JsonIgnore
    public String getName() {
        return userId.toString();
    }

    @Override
    public void eraseCredentials() {
        this.secret = null;
    }
}
