package com.cpop.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.cpop.core.base.entity.LoginUser;
import com.cpop.core.base.entity.loginInfo.OamStaffLoginInfo;
import com.cpop.core.base.enums.UserType;
import com.cpop.core.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author: DB
 * @date: 2022-09-26 23:06
 * @Description:
 */
public class SecurityUtils {

    private final static Logger logger = LoggerFactory.getLogger(SecurityUtils.class);

    private SecurityUtils() {
    }

    private static class securityUtilsInstance {
        private static final SecurityUtils INSTANCE = new SecurityUtils();
    }

    public static SecurityUtils getInstance() {
        return securityUtilsInstance.INSTANCE;
    }

    /**
     * @author LOST.yuan
     * @Description: 获取登录用户信息
     * @date 23:07 2022/9/26
     * @return {@link LoginUser}
     **/
    public LoginUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null){
            return null;
        }
        //匿名用户
        if (authentication.getPrincipal() == "anonymousUser") {
            return null;
        }
        if (null != authentication.getCredentials()) {
            return (LoginUser) authentication.getCredentials();
        } else {
            return (LoginUser) authentication.getDetails();
        }
    }

    /**
     * @descriptions 获取缓存用户信息
     * @author DB
     * @date 2023/09/21 16:00
     * @return com.cpop.core.base.entity.loginInfo.OamStaffLoginInfo
     */
    public JSONObject getLoginUserInfo() {
        //获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getInstance().getLoginUser();
        //系统内部进行程序没有用户
        if (loginUser == null) {
            return null;
        }
        //获取缓存信息
        JSONObject jsonObject = SpringUtils.getBean(RedisService.class).getCacheObject(loginUser.getUserType().getKey() + loginUser.getIdentification());
        return jsonObject.getJSONObject("user");
    }

}
