package cn.datax.common.utils;

import cn.datax.common.core.DataUser;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

public class SecurityUtil {

    /**
     * 获取用户
     *
     * @return user
     */
    public static DataUser getDataUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof DataUser) {
            DataUser user = (DataUser) principal;
            return user;
        }
        return null;
    }

    /**
     * 获取用户ID
     *
     * @return id
     */
    public static String getUserId() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof DataUser) {
            DataUser user = (DataUser) principal;
            return user.getId();
        }
        return null;
    }

    /**
     * 获取用户部门
     *
     * @return id
     */
    public static String getUserDeptId() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof DataUser) {
            DataUser user = (DataUser) principal;
            return user.getDept();
        }
        return null;
    }

    /**
     * 获取用户名称
     *
     * @return username
     */
    public static String getUserName() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof DataUser) {
            DataUser user = (DataUser) principal;
            return user.getUsername();
        }
        return null;
    }
}
