package com.ruoyi.common.apiencrypt.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.apiencrypt.annotation.ApiEncrypt;
import com.ruoyi.common.apiencrypt.enums.DataTypeEnum;
import com.ruoyi.common.apiencrypt.service.ApiEncryptService;
import com.ruoyi.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * 加密
 *
 * @Author 1024创新实验室
 * @Date 2023/10/24 09:52:58
 */
@Slf4j
@ControllerAdvice
public class EncryptResponseAdvice implements ResponseBodyAdvice<R<Object>> {

    @Resource
    private ApiEncryptService apiEncryptService;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.hasMethodAnnotation(ApiEncrypt.class) || returnType.getContainingClass().isAnnotationPresent(ApiEncrypt.class);
    }

    @Override
    public R<Object> beforeBodyWrite(R<Object> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null || body.getData() == null) {
            return body;
        }

        try {
            String encrypt = apiEncryptService.encrypt(objectMapper.writeValueAsString(body.getData()));
            body.setData(encrypt);
            body.setDataType(DataTypeEnum.ENCRYPT.getCode());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return body;
    }

}


