package com.qmth.teachcloud.common.util;

import com.qmth.teachcloud.common.contant.SystemConstant;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: http util
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/12/11
 */
public class HttpUtil {
    private final static Logger log = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * post 请求
     *
     * @param url
     * @param params
     * @param secret
     * @param timestamp
     * @return
     */
    public static String post(String url, Map<String, Object> params, String secret, Long timestamp) throws IOException {
        // 构建post请求
        HttpPost post = new HttpPost(url);
        post.setHeader(SystemConstant.HEADER_AUTHORIZATION, secret);
        post.setHeader(SystemConstant.HEADER_TIME, String.valueOf(timestamp));
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 构建请求参数
        List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                pairs.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
            }
        }
        HttpEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(pairs, SystemConstant.CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        post.setEntity(entity);
        // 执行请求，获取响应
        return getRespString(post);
    }

    /**
     * 获取响应信息
     *
     * @param request
     * @return
     */
    public static String getRespString(HttpUriRequest request) throws IOException {
        // 获取响应流
        InputStream in = null;
        ByteArrayOutputStream ou = null;
        try {
            in = getRespInputStream(request);
            ou = new ByteArrayOutputStream();
            IOUtils.copy(in, ou);
        } catch (Exception e) {
            log.error("请求出错", e);
        } finally {
            if (Objects.nonNull(in)) {
                in.close();
            }
            if (Objects.nonNull(ou)) {
                ou.close();
            }
        }
        return Objects.nonNull(ou) ? new String(ou.toByteArray(), StandardCharsets.UTF_8) : null;
    }

    /**
     * 获取输入流
     *
     * @param request
     * @return
     */
    public static InputStream getRespInputStream(HttpUriRequest request) {
        // 获取响应对象
        HttpResponse response = null;
        try {
            response = HttpClients.createDefault().execute(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (response == null) {
            return null;
        }
        // 获取Entity对象
        HttpEntity entity = response.getEntity();
        // 获取响应信息流
        InputStream in = null;
        if (entity != null) {
            try {
                in = entity.getContent();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return in;
    }
}