package org.springblade.common.auth;

import org.springblade.common.auth.permission.SessionIdContextUtil;
//import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author caiyihua
 */
@Slf4j
@Configuration
public class InvokeConfiguration {

    /**
     * 自定义请求拦截器，传递cookie
     *
     * @return
     */
//    @Bean
//    public RequestInterceptor myRequestInterceptor() {
//        return (requestTemplate) -> {
//            String sessionId = getSessionId();
//            requestTemplate.header("Cookie", "SESSION=" + sessionId);
//        };
//    }

    /**
     * 获取会话ID，默认优先获取系统显示配置的会话ID,获取不到则会调用系统默认的会话ID
     *
     * @return
     */
    private String getSessionId() {
        String sessionId = SessionIdContextUtil.getCurrentSessionId();
        if (StringUtils.isNotBlank(sessionId)) {
            return sessionId;
        }
        return getDefaultSessionId();
    }

    /**
     * 获取默认的会话ID，即当前用户正常登陆的会话ID
     */
    private String getDefaultSessionId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            log.error("Get attributes failed! Cannot get the default session ID...");
            return null;
        }
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        return session.getId();
    }
}
