package com.jiayue.ssi.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiayue.ssi.constant.SecretKeyConstants;
import com.jiayue.ssi.util.SM2CryptUtils;
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.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
* 返回值统一处理
*
* @author xsl
* @since 2023/03/03
*/
@ControllerAdvice(annotations = RestController.class)
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        ObjectMapper objectMapper = new ObjectMapper();
        String secretResult = "";
        try {
            String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
            // 加密处理
            String encrypt = SM2CryptUtils.encrypt(result, SecretKeyConstants.CLIENT_PUBLIC_KEY);
            // 签名
            String signStr = SM2CryptUtils.sign(SecretKeyConstants.SERVER_PRIVATE_KEY,result);

//            String encrypt = SM2CryptUtils.encrypt("1122", SecretKeyConstants.CLIENT_PUBLIC_KEY);
//            System.out.println("加密："+encrypt);
//            String signStr = SM2CryptUtils.sign(SecretKeyConstants.SERVER_PRIVATE_KEY,"1122");
//            System.out.println("签名："+signStr);
            // 解密
//            String text = SM2CryptUtils.decrypt(encrypt,SecretKeyConstants.CLIENT_PRIVATE_KEY);
//            System.out.println("解密："+text);
//            boolean bo = SM2CryptUtils.verifySign(SecretKeyConstants.SERVER_PUBLIC_KEY,text,signStr);
//            System.out.println("验签："+bo);
            secretResult = "returnData="+encrypt+"&returnSign="+signStr;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return secretResult;
    }
}
