package com.zcloud.common.ddos;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.SortedMap;
import java.util.TreeMap;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.TypeFactory;

@Slf4j
@UtilityClass
public class HttpDataUtil {
    /**
     * post请求处理：获取 Body 参数，转换为SortedMap
     *
     * @param request
     */
    private static final ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        // 启用特性使序列化输出的Map和集合保持有序
        objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
    }

    public static SortedMap<String, Object> getBodyParams(final HttpServletRequest request) throws IOException {
        byte[] requestBody = StreamUtils.copyToByteArray(request.getInputStream());
        String body = new String(requestBody);

        // 使用自定义配置的ObjectMapper解析JSON为SortedMap，注意这里简化处理，实际可能需要更复杂的TypeReference来准确映射所有可能的嵌套结构
        SortedMap<String, Object> params = objectMapper.readValue(body,
                TypeFactory.defaultInstance().constructMapType(SortedMap.class, String.class, Object.class));

        return params;
    }

    /**
     * get请求处理：将URL请求参数转换成SortedMap
     */
    public static SortedMap<String, Object> getUrlParams(HttpServletRequest request) {
        String param = "";
        SortedMap<String, Object> result = new TreeMap<>();

        if (StringUtils.isEmpty(request.getQueryString())) {
            return result;
        }

        try {
            param = URLDecoder.decode(request.getQueryString(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String[] params = param.split("&");
        for (String s : params) {
            String[] array=s.split("=");
            result.put(array[0], array[1]);
        }
        return result;
    }
}
