package com.cpop.core.base.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.cpop.common.utils.StringUtils;
import com.cpop.core.base.enums.UserType;
import com.cpop.core.base.table.SysUser;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;

/**
 * 登录用户身份权限
 *
 * @author DB
 */
@Data
@Accessors(chain = true)
public class LoginUser implements UserDetails {

    /**
     * 用户ID
     */
    private String userId;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 用户唯一标识
     */
    private String identification;

    /**
     * 登录时间
     */
    private Long loginTime = System.currentTimeMillis();

    /**
     * 过期时间
     */
    private Long expireTime;

    /**
     * 登录IP地址
     */
    private String ipAddr;

    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 权限列表
     */
    private Set<String> permissions;

    /**
     * 用户信息
     */
    private SysUser user;

    /**
     * 消息
     */
    private String msg;

    /**
     * 登录状态
     */
    private Boolean status;

    /**
     * 用户类型
     */
    private UserType userType = UserType.OAM_USER;

    public LoginUser() {
    }

    public LoginUser(SysUser user,String identification, Set<String> permissions) {
        this.user = user;
        this.identification = identification;
        this.permissions = permissions;
    }

    public LoginUser(String userId, SysUser user, Set<String> permissions) {
        this.userId = userId;
        this.user = user;
        this.permissions = permissions;
    }

    @JSONField(serialize = false)
    @Override
    public String getPassword() {
        return user.getPassword();
    }


    @Override
    public String getUsername() {
        if (StringUtils.isBlank(this.userName)){
            return user.getUserName();
        }else {
            return this.userName;
        }
    }

    /**
     * 账户是否未过期,过期无法验证
     */
    @JSONField(serialize = false)
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 指定用户是否解锁,锁定的用户无法进行身份验证
     */
    @JSONField(serialize = false)
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
     */
    @JSONField(serialize = false)
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否可用 ,禁用的用户不能身份验证
     */
    @JSONField(serialize = false)
    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //根据自定义逻辑来返回用户权限，如果用户权限返回空或者和拦截路径对应权限不同，验证不通过;自定义权限注解，此处设定为null
        return null;
    }
}
