package org.jeecg.modules.shop.user.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.PartnerUserLoginUser;
import org.jeecg.config.shiro.PartnerToken;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public abstract class partnerUserHolder {
    
    /**
     * 判断当前请求是否是登录状态，如果不是，判断是否可以登录
     */
    public static boolean isAuthenticatedOrIsCanLogin() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return true;
        }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (null == requestAttributes) {
            return false;
        }
        try {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
            SecurityUtils.getSubject().login(new PartnerToken(token));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String currentLoginUserId() {
        if (!SecurityUtils.getSubject().isAuthenticated()) {
           throw new RuntimeException("Token失效，请重新登录!");
        }
        Object principal = SecurityUtils.getSubject().getPrincipal();
        if (!(principal instanceof PartnerUserLoginUser)) {
            throw new RuntimeException("Token异常!");
        }
        String uid = ((PartnerUserLoginUser) principal).getId();
        Assert.isTrue(StrUtil.isNotBlank(uid), "Token失效，请重新登录!");
        return uid;
    }
    
}
