package com.tzy.common.core.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tzy.common.annotation.JsonParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

@Slf4j
//@Component
public class JsonParamArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        JsonParam annotation = parameter.getParameterAnnotation(JsonParam.class);
        Object object = null;
        if (annotation != null) {
            String parameterName = annotation.value();
            if (StringUtils.isBlank(parameterName)) {
                parameterName = parameter.getParameterName();
            }
            HttpServletRequest req = ((ServletWebRequest) webRequest).getRequest();
            String value = req.getReader().lines().collect(Collectors.joining());
            //String value = webRequest.getParameter(parameterName);
            if (StringUtils.isNotBlank(value)) {
                JSONObject body = JSON.parseObject(value);
                value=JSON.toJSONString(body.get("data"));
                Class<?> objectType = annotation.objectType();
                try {
                    if (objectType != JsonParam.class) {
                        object = JSON.parseArray(value, objectType);
                    } else {
                        object = JSON.parseObject(value, parameter.getParameterType());
                    }
                } catch (Exception e) {
                    log.error("参数Json转换失败:" + parameter.getContainingClass().getName() + "." + parameter.getMethod().getName() + "[" + parameterName + "]");
                }
            }
            mavContainer.addAttribute(parameterName, object);
        }
        return object;
    }
}