package com.koobietech.eas.common.utils;

import com.koobietech.eas.dao.constant.UserType;
import com.koobietech.eas.dao.pojo.UserDetailPojo;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * @author lc
 */
public class SecurityManager {

    /**
     * 取登录名
     * @return
     */
    public static String getLoginUserName() {
        UserDetailPojo principal = getPrincipal();
        if (Objects.nonNull(principal)) {
            return principal.getUsername();
        }
        return "anonymousUser";
    }

    /**
     * 取用户ID
     * @return
     */
    public static Long getLoginUid() {
        UserDetailPojo principal = getPrincipal();
        if (Objects.nonNull(principal)) {
            if ( !isStudentUser() ) {
                return principal.getId();
            }
        }
        return 0L;
    }

    /**
     * 判断是否是学员
     * @return
     */
    public static boolean isStudentUser() {
        boolean isStudent = false;
        UserDetailPojo principal = getPrincipal();
        if (Objects.nonNull(principal)) {
            if ( principal.getUserType().equals(UserType.MEMBER) ) {
                isStudent = true;
            }
        }
        return isStudent;
    }

    /**
     * 取学员登录ID
     * @return
     */
    public static Long getLoginSid() {
        UserDetailPojo principal = getPrincipal();
        if (Objects.nonNull(principal)) {
            if ( isStudentUser() ) {
                return principal.getId();
            }
        }
        return 0L;
    }

    /**
     * 是否登录
     * @return
     */
    public static boolean isLogged() {
        UserDetailPojo principal = getPrincipal();
        return Objects.nonNull(principal);
    }

    private static UserDetailPojo getPrincipal() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (Objects.nonNull(principal)) {
            if (principal instanceof UserDetailPojo) {
                return (UserDetailPojo) principal;
            } else {
                return null;
            }
        }
        return null;
    }
}
