package com.jeequan.jeepay.mgr.web;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.utils.ApiResBodyAdviceKit;
import com.jeequan.jeepay.core.utils.JsonKit;
import com.jeequan.jeepay.service.impl.SysConfigService;
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.servlet.mvc.method.annotation.ResponseBodyAdvice;

/*
* 功能： 自定义springMVC返回数据格式
*
* @author terrfly
* @date 2021/6/8 17:12
*/
@ControllerAdvice
public class ApiResBodyAdvice implements ResponseBodyAdvice {

    /** 判断哪些需要拦截 **/
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    /** 拦截返回数据处理 */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {


        // 如果为 ApiRes && code为成功态 根据设置做数据传输的加密项  && 系统配置的为传输加密
        if( body instanceof ApiRes && ((ApiRes)body).getCode() != null && ((ApiRes)body).getCode().equals(ApiCodeEnum.SUCCESS.getCode())
            && SysConfigService.HTTP_MSG_IS_ENCRYPT
        ){

            // 获取到转换后的格式，并且转回ApiRes
            ApiRes result = ((JSONObject)ApiResBodyAdviceKit.beforeBodyWrite(body)).toJavaObject(ApiRes.class);
            if(result.getData() != null){ //若原始数据不为空
                result.setEncryptData(SysConfigService.HTTP_MESSAGE_ENCRYPT_SM4.encryptBase64(JsonKit.newJson("originData", result.getData()).toJSONString()));
                result.setData(null);
            }
            return result;
        }

        //处理扩展字段
        return ApiResBodyAdviceKit.beforeBodyWrite(body);
    }

}
