package com.jeequan.jeepay.member.secruity;

import com.jeequan.jeepay.db.entity.MemberInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

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

/**
 * 实现Spring Security的UserDetails接口
 *
 * @author zx
 * @date 2023/4/8 16:34
 */
@Slf4j
@Data
public class JeeMemberDetails implements UserDetails {

    /**
     * 会员信息
     **/
    private MemberInfo memberInfo;

    /**
     * 密码
     **/
    private String credential;

    /**
     * 角色+权限 集合   （角色必须以： ROLE_ 开头）
     **/
    private Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();

    /**
     * 缓存标志
     **/
    private String cacheKey;

    /**
     * 登录IP
     **/
    private String loginIp;

    /**
     * 认证类型，见  CREDENTIAL_AUTH_TYPE
     **/
    private String authType;

    //此处的无参构造，为json反序列化提供
    public JeeMemberDetails() {
    }

    public JeeMemberDetails(MemberInfo memberInfo) {
        this.setMemberInfo(memberInfo);
    }

    /**
     * spring-security 需要验证的密码
     **/
    @Override
    public String getPassword() {
        return getCredential();
    }

    /**
     * spring-security 登录名
     **/
    @Override
    public String getUsername() {
        return getMemberInfo().getMbrId();
    }

    /**
     * 账户是否过期
     **/
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账户是否已解锁
     **/
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 密码是否过期
     **/
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账户是否开启
     **/
    @Override
    public boolean isEnabled() {
        return true;
    }

    /**
     * 获取权限集合
     **/
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    public static JeeMemberDetails getCurrentMemberDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }

        try {
            return (JeeMemberDetails) authentication.getPrincipal();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前登录者ID
     **/
    public String getMbrId() {
        return this.getMemberInfo() != null ? this.getMemberInfo().getMbrId() : null;
    }

}
