package com.tykj.workflowcore.user.util;

import com.tykj.workflowcore.user.pojo.User;
import com.tykj.workflowcore.user.pojo.UserDetail;
import com.tykj.workflowcore.user.service.CenterUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 用户实体相关工具类
 *
 * @author HuangXiahao
 * @version V1.0
 * @class AuthenticationUtils
 * @packageName com.example.personnelmanager.common.utils
 * @data 2020/5/14
 **/
@Slf4j
@Component
public class AuthenticationUtils {

    public static String ANONYMOUS_USER_STRING = "anonymousUser";

    private final CenterUserService centerUserService;

    public AuthenticationUtils(CenterUserService centerUserService) {
        this.centerUserService = centerUserService;
    }

    /***
     * 获取当前登录用户
     *
     * @Return : com.example.personnelmanager.entity.UserDetail
     */
    public UserDetail getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object userObject = authentication.getPrincipal();
            if (ANONYMOUS_USER_STRING.equals(userObject)) {
                log.info("当前无登录用户");
                return null;
            }
            if (userObject instanceof UserDetail) {
                return (UserDetail) userObject;
            } else {
                return centerUserService.getUserDetail(((User) userObject).getUsername());
            }
        } else {
            return null;
        }
    }

}
