package com.tuoheng.system.utils;

import cn.hutool.core.util.ObjectUtil;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.SpringUtils;
import com.tuoheng.system.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.http.HttpStatus;

import java.util.Optional;

/**
 * Shiro工具类
 */
public class ShiroUtils {

    /**
     * 私有构造器
     **/
    private ShiroUtils() {
    }

    private static RedisSessionDAO redisSessionDAO = SpringUtils.getBean(RedisSessionDAO.class);

    /**
     * 获取当前用户Session
     *
     * @return
     */
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 用户退出
     */
    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    public static User getUserInfo() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(ObjectUtil.isEmpty(user)){
            throw new ServiceException(HttpStatus.UNAUTHORIZED.value(), "请先登录");
        }
        return user;
    }

    /**
     * 获取用户编号
     *
     * @return
     */
    public static Integer getUserId() throws ServiceException {
        User user = getUserInfo();
        if(ObjectUtil.isEmpty(user)){
            throw new ServiceException(HttpStatus.UNAUTHORIZED.value(), "请先登录");
        }
        return Optional.ofNullable(user.getId()).orElseThrow(() ->
                new ServiceException(HttpStatus.BAD_REQUEST.value(), "未获取到当前用户信息!"));
    }

    /**
     * 租户ID
     *
     * @return
     */
    public static Integer getTenantId() {
        User user = getUserInfo();
        if(ObjectUtil.isEmpty(user)){
            throw new ServiceException(HttpStatus.UNAUTHORIZED.value(), "请先登录");
        }
        return Optional.ofNullable(user.getTenantId()).orElseThrow(() ->
                new ServiceException(HttpStatus.BAD_REQUEST.value(), "未获取到当前租户信息!"));
    }
}
