package cn.superdesk.uniorder.common.security.superdeskapp.sign;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.Map;

/**
 * 服务之窗1L- ExtRequestBodyArgumentResolver
 *
 * @Description TODO
 * @author: jiangyong
 * @since: 2020/9/22 14:33
 */
public class OpenDataApiRequestBodyArgumentResolver implements HandlerMethodArgumentResolver {


	@Override
	public boolean supportsParameter(MethodParameter methodParameter) {
		return methodParameter.hasParameterAnnotation(OpenDataApiRequestBody.class);
	}

	@Override
	public Object resolveArgument(MethodParameter methodParameter,
	                              ModelAndViewContainer modelAndViewContainer,
	                              NativeWebRequest nativeWebRequest,
	                              WebDataBinderFactory webDataBinderFactory) throws Exception {

		HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

		//解析content中的业务参数
		String paramterJson = nativeWebRequest.getParameter("content");

//        paramterJson = AESUtils.decrypt(paramterJson,"");

		Map<String, Object> paramMap = JSON.parseObject(paramterJson, Map.class);
		paramMap.putAll(getParamterMap(request));

		final Type   type = methodParameter.getGenericParameterType();
		final Object o    = JSON.parseObject(JSON.toJSONString(paramMap), type);
		return o;
	}

	/**
	 * 迭代的方式获取所有paramter
	 *
	 * @param request
	 * @return
	 */
	private Map<String, Object> getParamterMap(HttpServletRequest request) {
		Enumeration<String> parameterNames = request.getParameterNames();
		Map<String, Object> paramterMap    = new HashedMap();

		if (null != parameterNames) {

			while (parameterNames.hasMoreElements()) {
				String en    = parameterNames.nextElement();
				String value = request.getParameter(en);

				if (!(en == null || en.length() == 0 || "content".equals(en))) {
					paramterMap.put(en, value);
				}
			}

		}
		return paramterMap;
	}


}
