package com.eitc.common.filter;

import com.alibaba.fastjson2.JSON;
import com.eitc.common.annotation.IgnoreReturnResultEncryption;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.core.page.TableDataInfo;
import com.eitc.common.utils.CryptoUtil;
import lombok.extern.slf4j.Slf4j;
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;

import java.lang.reflect.Method;
import java.util.Objects;


@ControllerAdvice
@Slf4j
public class CustomResponseBodyAdviceAdapter implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        Method method = returnType.getMethod();
        assert method != null;
        IgnoreReturnResultEncryption ra = method.getAnnotation(IgnoreReturnResultEncryption.class);
        return Objects.isNull(ra);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof AjaxResult) {
            AjaxResult ajaxResult = (AjaxResult) body;
            try {
                return CryptoUtil.encrypt(JSON.toJSONString(ajaxResult));
            } catch (Exception e) {
                log.error("AjaxResult加密失败：" + body, e);
                return ajaxResult;
            }
        } else if (body instanceof TableDataInfo) {
            TableDataInfo tableDataInfo = (TableDataInfo) body;
            try {
                return CryptoUtil.encrypt(JSON.toJSONString(tableDataInfo));
            } catch (Exception e) {
                log.error("TableDataInfo加密失败：" + body, e);
                return tableDataInfo;
            }
        }
        return body;
    }
}
