package com.lantone.userauth.domain;

import com.lantone.common.domain.UserDto;
import com.lantone.common.enums.StatusEnum;
import com.lantone.common.util.ListUtil;
import com.lantone.common.util.StringUtil;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @Description: 登录用户信息
 * @author: rengb
 * @time: 2021/1/5 18:27
 */
@Data
public class SecurityUser implements UserDetails {

    /**
     * ID
     */
    private Long id;
    /**
     * 用户名
     */
    private String userName;
    /**
     * 用户密码
     */
    private String password;
    /**
     * 用户状态
     */
    private String status;
    /**
     * 登录客户端ID
     */
    private String clientId;
    /**
     * 权限数据
     */
    private Collection<SimpleGrantedAuthority> authorities;

    public SecurityUser(UserDto userDto) {
        this.setId(userDto.getId());
        this.setUserName(userDto.getUserName());
        this.setPassword(userDto.getPassword());
        this.setStatus(userDto.getStatus());
        this.setClientId(userDto.getClientId());
        if (ListUtil.isNotEmpty(userDto.getRoles())) {
            authorities = new ArrayList<>();
            userDto.getRoles().forEach(item -> authorities.add(new SimpleGrantedAuthority(item)));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

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

    @Override
    public String getUsername() {
        return this.userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return StringUtil.isNotBlank(this.status) && this.status.equals(StatusEnum.Enable.getKey());
    }

}