
package com.qs.mp.handler;

import com.alibaba.fastjson.JSONObject;
import com.qs.mp.common.enums.HttpMethod;
import com.qs.mp.common.utils.LogUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpHelper {

  protected static final Logger logger = LoggerFactory.getLogger(HttpHelper.class);

  /**
   * requestbody 解析
   *
   * @param request
   * @return
   */
  public static String getBodyString(ServletRequest request) {
    StringBuilder sb = new StringBuilder();
    InputStream inputStream = null;
    BufferedReader reader = null;
    try {
      inputStream = request.getInputStream();
      reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
      String line = "";
      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }
    } catch (IOException e) {
      LogUtil.error(logger,"Stream to String error", e);
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          LogUtil.error(logger,"Stream to String error", e);
        }
      }
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          LogUtil.error(logger,"Stream to String error", e);
        }
      }
    }
    return sb.toString();
  }

  public static SortedMap<String, String> getAllParams(HttpServletRequest request)
      throws IOException {

    SortedMap<String, String> result = new TreeMap<>();
    //获取URL上的参数
    Map<String, String> urlParams = getUrlParams(request);
    for (Map.Entry entry : urlParams.entrySet()) {
      result.put((String) entry.getKey(), (String) entry.getValue());
    }
    Map<String, String> allRequestParam = new HashMap<>(16);
    // get请求不需要拿body参数
    if (!HttpMethod.GET.name().equals(request.getMethod())) {
      allRequestParam = getAllRequestParam(request);
    }
    //将URL的参数和body参数进行合并
    if (allRequestParam != null) {
      for (Map.Entry entry : allRequestParam.entrySet()) {
        result.put((String) entry.getKey(), (String) entry.getValue());
      }
    }
    return result;
  }

  /**
   * 获取 Body 参数
   *
   * @param request
   * @author show
   * @date 15:04 2019/5/30
   */
  public static Map<String, String> getAllRequestParam(final HttpServletRequest request)
      throws IOException {

    BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String str = "";
    StringBuilder wholeStr = new StringBuilder();
    //一行一行的读取body体里面的内容；
    while ((str = reader.readLine()) != null) {
      wholeStr.append(str);
    }
    //转化成json对象
    return JSONObject.parseObject(wholeStr.toString(), Map.class);
  }

  /**
   * 将URL请求参数转换成Map
   *
   * @param request
   * @author show
   */
  public static Map<String, String> getUrlParams(HttpServletRequest request) {

    String param = "";
    try {
      param = URLDecoder.decode(request.getQueryString(), "utf-8");
    } catch (UnsupportedEncodingException e) {
      LogUtil.error(logger,"", e);
    }
    Map<String, String> result = new HashMap<>(16);
    String[] params = param.split("&");
    for (String s : params) {
      int index = s.indexOf("=");
      result.put(s.substring(0, index), s.substring(index + 1));
    }
    return result;
  }

}
