package cc.smtweb.framework.core.mvc.controller;

import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.session.SessionUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created by Akmm at 2022-09-08 16:03
 * 统一添加指纹
 */
@ControllerAdvice
public class SwResponseBodyAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        Class targetClass = returnType.getMethod().getDeclaringClass();

        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof R) {
            SessionUtil.setFingerValue(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(), (R)body);
        }
        return body;
    }
}
