package cn.reghao.autodop.dmaster.rbac.model.po;

import cn.reghao.autodop.dmaster.util.db.BaseEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Collection;
import java.util.Set;

/**
 * 用户
 *
 * @author reghao
 * @date 2019/03/14 19:12:48
 */
@NoArgsConstructor
@Getter
@Setter
@Entity
public class User extends BaseEntity<Integer> implements UserDetails {
    // 用户名和密码
    @Column(nullable = false, unique = true)
    @NotBlank(message = "用户名不能为空白字符串")
    private String username;
    @Column(nullable = false)
    @JsonIgnore
    @NotBlank(message = "密码不能为空白字符串")
    private String password;
    @Column(nullable = false)
    private String salt;
    // roles 和 authorities 是同一个东东, 只是 authorities 用于 Spring Security
    @ElementCollection(fetch = FetchType.EAGER)
    private Set<String> role;
    @Transient
    private Set<UserAuthority> authorities;
    private Boolean isEnabled;
    private Boolean isLocked;

    @NotBlank(message = "标题不能为空白字符串")
    private String nickname;
    private String avatarUrl;
    private String mobilePhone;
    private String email;
    private Integer gender;

    public User(String username, Set<UserAuthority> authorities) {
        this.username = username;
        this.authorities = authorities;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    /**
     * 账户是否未过期
     *
     * @param
     * @return
     * @date 2019-05-29 下午2:05
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 密码是否未过期
     *
     * @param
     * @return
     * @date 2019-05-29 下午2:05
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账户是否可用
     *
     * @param
     * @return
     * @date 2019-05-29 下午2:05
     */
    @Override
    public boolean isEnabled() {
        return isEnabled;
    }

    /**
     * 账户是否锁定
     *
     * @param
     * @return
     * @date 2019-05-29 下午2:05
     */
    @Override
    public boolean isAccountNonLocked() {
        return isLocked;
    }

    /**
     * 权限列表
     *
     * @param
     * @return
     * @date 2019-05-29 下午2:22
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    public Set<UserAuthority> getAuthoritiesSet() {
        return authorities;
    }
}
