package com.lightinit.hsdatagateway.modules.foreign.util;


import com.lightinit.hsdatagateway.common.exceptions.HttpTransferErrorException;
import com.lightinit.hsdatagateway.modules.foreign.model.RequestDto;
import com.lightinit.hsdatagateway.modules.foreign.model.ResponseModel;
import com.lightinit.hsdatagateway.modules.foreign.model.RequestDto;
import com.lightinit.hsdatagateway.modules.foreign.model.ResponseModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Author: yangrui
 * @Date: 2019/3/4 16:30
 */
public class HttpUtil {


    /**
     * 发送http get请求
     */
    public static ResponseModel httpGet(CloseableHttpClient httpClient, String url, Map<String, String> param, String encode) {
        HttpGet httpGet = new HttpGet(StringUtils.join(url, "?", buildParam(param)));
        return execute(httpClient, httpGet, encode);
    }


    /**
     * 发送 http post 请求，参数以form表单键值对的形式提交。
     */
    public static ResponseModel httpPostForm(CloseableHttpClient httpClient, RequestDto requestDto, String encode) {
        HttpPost httPost = new HttpPost(requestDto.getUrl());
        httPost.addHeader("Content-Type", requestDto.getContentType());
        if (verifyIsFormData(requestDto.getContentType())) {
            //组织请求参数
            List<NameValuePair> paramList = new ArrayList<>();
            Map<String, String> params = requestDto.getParam();
            if (params != null && params.size() > 0) {
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    paramList.add(new BasicNameValuePair(key, params.get(key)));
                }
            }
            try {
                httPost.setEntity(new UrlEncodedFormEntity(paramList, encode));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        } else {
            //组织请求参数
            StringEntity stringEntity = new StringEntity(requestDto.getBody(), encode);
            stringEntity.setContentType(requestDto.getContentType());
            httPost.setEntity(stringEntity);
        }


        return execute(httpClient, httPost, encode);
    }


    /**
     * 发送 http put 请求，参数以原生字符串进行提交
     *
     * @param url
     * @param encode
     * @return
     */
    public static ResponseModel httpPut(CloseableHttpClient httpClient, String url, String stringJson, String contentType, String encode) {
        HttpPut httpPut = new HttpPut(url);
        //组织请求参数
        StringEntity stringEntity = new StringEntity(stringJson, encode);
        httpPut.setEntity(stringEntity);
        stringEntity.setContentType(contentType);
        return execute(httpClient, httpPut, encode);
    }


    /**
     * 发送http delete请求
     */
    public static ResponseModel httpDelete(CloseableHttpClient httpClient, String url, Map<String, String> param, String encode) {
        HttpDelete httpdelete = new HttpDelete(StringUtils.join(url, "?", buildParam(param)));
        return execute(httpClient, httpdelete, encode);
    }


    private static ResponseModel execute(CloseableHttpClient httpClient, HttpRequestBase httpRequestBase, String encode) {
        if (encode == null) {
            encode = "utf-8";
        }
        ResponseModel responseModel = new ResponseModel();
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpRequestBase);
            HttpEntity entity = httpResponse.getEntity();
            String content = EntityUtils.toString(entity, encode);
            responseModel.setContentType(entity.getContentType().getValue());
            responseModel.setBody(content);
            responseModel.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
            responseModel.setCode(httpResponse.getStatusLine().getStatusCode());
        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpTransferErrorException(e.getMessage());
        } finally {
            try {
                if (Objects.nonNull(httpResponse)) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseModel;
    }


    private static String buildParam(Map<String, String> param) {
        String reduce = param.entrySet().stream().map(entry -> StringUtils.join(entry.getKey(), "=", entry.getValue())).reduce("", (join, item) -> {
            if (StringUtils.isBlank(join)) {
                return item;
            } else {
                return StringUtils.join(join, "&", item);
            }
        }, (a, b) -> a + b);
        return reduce;
    }

    public static boolean verifyIsFormData(String type) {
        return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
    }

}
