//package com.storlead.framework.web.process;
//
//import com.fasterxml.jackson.core.JsonParser;
//import com.fasterxml.jackson.databind.DeserializationFeature;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.storlead.framework.common.result.Result;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.core.MethodParameter;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//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;
//
//import java.lang.reflect.AnnotatedElement;
//import java.lang.reflect.Array;
//import java.util.*;
//
//@ControllerAdvice
//public class ApiResultHandler implements ResponseBodyAdvice<Object> {
//    private List<String> modulePackages;
//
//    private static final Class[] annos = {
//            RequestMapping.class
//            , GetMapping.class
//            , PostMapping.class
//            , DeleteMapping.class
//            , PutMapping.class
//    };
//
////    @Override
////    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
////        return supports(returnType, modulePackages);
////    }
//
//    @Override
//    public boolean supports(MethodParameter returnType, Class converterType) {
//        // 不处理 ResponseEntity 返回值，避免图片/文件流等被包装导致 ClassCastException
//        if (ResponseEntity.class.isAssignableFrom(returnType.getParameterType())) {
//            return false;
//        }
//        AnnotatedElement element = returnType.getAnnotatedElement();
//        return Arrays.stream(annos).anyMatch(anno -> anno.isAnnotation() && element.isAnnotationPresent(anno));
//    }
//
////    public static boolean supports(MethodParameter returnType, List<String> modulePackages) {
////        Class<?> declaringClass = returnType.getDeclaringClass();
////        return belongOwn(modulePackages, declaringClass.getPackage().getName());
//////                declaringClass.getAnnotation(UnWarp.class) == null
//////                && returnType.getMethodAnnotation(Unwrap.class) == null
//////                && belongOwn(modulePackages, declaringClass.getPackage().getName());
////    }
//
//    public static boolean belongOwn(List<String> modulePackages, String declaringPackageName) {
//        for (String modulePackage : modulePackages) {
//            if (declaringPackageName.startsWith(modulePackage)) {
//                return true;
//            }
//        }
//        return false;
//    }
//
//    /**
//     * 数据返回之前   处理数据
//     **/
//    @Override
//    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
//                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
//                                  ServerHttpResponse response) {
//        Object data = normalizeResult(body);
//        data = wrapIfNeed(data, returnType);
//        data = normalizeResult(data);
//
//
//        String selectedConverterTypeClassName = selectedConverterType.getName();
//        // selectedConverterType 对象是  StringHttpMessageConverter时， 表示不能直接返回  WebResp, 要不然会报错      org.springframework.http.converter.StringHttpMessageConverter
//        if (selectedConverterTypeClassName.indexOf("StringHttpMessageConverter") >= 0) {    // 如果是返回  string 类型的， 就返回 string 类型的
//            if (data instanceof Result) {
//                ObjectMapper mapper = new ObjectMapper();
//                mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//                mapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
//                mapper.enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
//                mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
//                try {
//                    return mapper.writeValueAsString(data);
//                } catch (Exception e) {
//                    return data;
//                }
//            } else {
//                return data;
//            }
//        } else {    // 返回 对象的
//            return data;
//        }
//    }
//
//    public static Object wrapIfNeed(Object body, MethodParameter returnType) {
//        // 对于已经是统一返回类型的结果或资源类，直接透传，避免二次包装导致类型转换异常
//        if (body instanceof Result) {
//            return normalizeResult(body);
//        } else if (body instanceof org.springframework.core.io.Resource) {
//            // 文件预览/下载等场景需要直接返回二进制流
//            return body;
//        } else if (body instanceof org.springframework.http.ResponseEntity) {
//            // ResponseEntity 如 404、图片预览等，直接透传，避免包装导致序列化异常
//            org.springframework.http.ResponseEntity<?> resp = (org.springframework.http.ResponseEntity<?>) body;
//            Object respBody = resp.getBody();
//            if (respBody == null || respBody instanceof org.springframework.core.io.Resource) {
//                return body;
//            }
//        }
//        {
//            if (body != null) {
//                return Result.result(body);
//            } else if(body == null) {
//                return Result.ok();
//            }
//            return Result.result(getDefaultValue(returnType));
//        }
//    }
//
//    /**
//     * fastjson.JSONObject 若被 Jackson 当作 Bean 序列化会产生乱码；统一转为普通 Map。
//     */
//    private static Object normalizeResult(Object body) {
//        if (!(body instanceof Result)) {
//            return body;
//        }
//        Result<?> result = (Result<?>) body;
//        Object payload = result.getResult();
//        if (payload instanceof JSONObject) {
//            result.setResult(JSON.parseObject(JSON.toJSONString(payload)));
//        }
//        return result;
//    }
//
//    public static Object getDefaultValue(MethodParameter returnType) {
//        Class<?> bodyType = returnType.getParameterType();
//        return getDefaultValue(bodyType);
//    }
//
//    private static Object getDefaultValue(Class<?> bodyType) {
//        final Object body;
//        if (bodyType.isArray()) {
//            body = Array.newInstance(bodyType.getComponentType(), 0);
//        } else if (List.class.isAssignableFrom(bodyType)) {
//            body = Collections.emptyList();
//        } else if (Set.class.isAssignableFrom(bodyType)) {
//            body = Collections.emptySet();
//        } else if (Map.class.isAssignableFrom(bodyType)) {
//            body = Collections.emptyMap();
//        } else if (String.class.isAssignableFrom(bodyType)) {
//            body = StringUtils.EMPTY;
//        } else {
//            body = bodyType;
//        }
//        return body;
//    }
//
////BeansException
////    @Override
////    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
//////        List<String> modulePackages = FrameworkAutoConfigurationPackages.get(beanFactory);
//////        List<String> modulePackageList = new ArrayList<>(modulePackages.size() + 1);
//////        modulePackageList.addAll(modulePackages);
//////        modulePackageList.add(PageResp.class.getPackage().getName());
////        this.modulePackages = null;//= modulePackageList;
////    }
//}
