package cn.qg.qaplatform.utils;

import com.alibaba.fastjson.JSONException;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.JsonExpression;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

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

import com.alibaba.fastjson.JSONObject;

/**
 * Http请求工具类
 * @author libo
 */
@Slf4j
public class HttpClientUtils {

    private static final CloseableHttpClient client = HttpClients.createDefault();

    /**
     * 不带参数的GET请求
     * @param url 请求的url
     * @return json
     */
    public static JSONObject doGetReturnJson(String url) {
        JSONObject jsonResult = new JSONObject();
        HttpGet get = new HttpGet(url);
        try {
            CloseableHttpResponse response = client.execute(get);
            HttpEntity httpEntity = response.getEntity();
            String respStr = EntityUtils.toString(httpEntity, "utf-8");
            jsonResult = JSONObject.parseObject(respStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    /**
     * 不带参数的GET请求
     * @param url 请求的url
     * @return html代码
     */
    public static String doGetReturnHtml(String url) {
        String strResult = null;
        HttpGet get = new HttpGet(url);
        try {
            CloseableHttpResponse response = client.execute(get);
            HttpEntity httpEntity = response.getEntity();
            strResult = EntityUtils.toString(httpEntity, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strResult;
    }

    /**
     * 带参数的GET请求
     * @param url 请求url
     * @param params 请求参数
     * @param headers 请求头
     * @throws URISyntaxException
     * @return
     */
    public static String doGetReturnHtml(String url, Map<String, Object> params, Map<String, Object> headers) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);
        String strResult = null;
        // 设置请求参数
        if (params != null && !params.isEmpty()) {
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                uriBuilder.setParameter(key, params.get(key).toString());
            }
        }
        HttpGet get = new HttpGet(uriBuilder.build());
        // 设置请求头
        if (headers != null && !headers.isEmpty()) {
            Set<String> keySet = headers.keySet();
            for (String s : keySet) {
                get.addHeader(s, headers.get(s).toString());
            }
        }
        try {
            CloseableHttpResponse response = client.execute(get);
            HttpEntity httpEntity = response.getEntity();
            strResult = EntityUtils.toString(httpEntity, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strResult;
    }

    /**
     * 带参数的GET请求
     * @param url url
     * @param params 参数
     * @param headers 请求头
     * @return json
     * @throws URISyntaxException
     */
    public static JSONObject doGetReturnJson(String url, Map<String, Object> params, Map<String, Object> headers) throws URISyntaxException {
        JSONObject jsonResult = new JSONObject();
        URIBuilder uriBuilder = new URIBuilder(url);
        // 设置参数
        if (params != null && !params.isEmpty()) {
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                uriBuilder.setParameter(key, params.get(key).toString());
            }
        }
        HttpGet get = new HttpGet(uriBuilder.build());
        if (headers != null && !headers.isEmpty()) {
            Set<String> keySet = headers.keySet();
            for (String s : keySet) {
                get.addHeader(s, headers.get(s).toString());
            }
        }
        try {
            CloseableHttpResponse response = client.execute(get);
            HttpEntity httpEntity = response.getEntity();
            String respStr = EntityUtils.toString(httpEntity, "utf-8");
            jsonResult = JSONObject.parseObject(respStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    /**
     * 带参数的post请求
     * @param url
     * @param params
     * @return
     */
    public static JSONObject doPost(String url, String params) {
        JSONObject jsonResult = new JSONObject();
        try {
            HttpPost post = new HttpPost(url);
            List<NameValuePair> list = new ArrayList<>();
            if (StringUtils.isNotEmpty(params)) {
                String[] splitStrings = params.split("&");
                for (String splitString : splitStrings) {
                    String[] split = splitString.split("=");
                    list.add(new BasicNameValuePair(split[0], split[1]));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
                post.setEntity(urlEncodedFormEntity);
            }
            CloseableHttpResponse response = client.execute(post);
            HttpEntity responseEntity = response.getEntity();
            String responseString = EntityUtils.toString(responseEntity, "utf-8");
            try {
                jsonResult = JSONObject.parseObject(responseString);
            } catch (JSONException e) {
                jsonResult.put("content", responseString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    public static JSONObject doPost(String url, Map<String, Object> params) {
        JSONObject jsonResult = new JSONObject();
        try {
            HttpPost post = new HttpPost(url);
            List list = new ArrayList();
            if (params != null && !params.isEmpty()) {
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    list.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity =
                        new UrlEncodedFormEntity(list, "utf-8");
                post.setEntity(urlEncodedFormEntity);
            }
            CloseableHttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            String respEntity = EntityUtils.toString(entity, "utf-8");
            try {
                jsonResult = JSONObject.parseObject(respEntity);
            } catch (JSONException e) {
//                e.printStackTrace();
                jsonResult.put("content", respEntity.toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    public static JSONObject doPost(String url, Map<String, Object> params, Map<String, Object> headers) {
        JSONObject jsonResult = new JSONObject();
        String responseString = null;
        try {
            HttpPost post = new HttpPost(url);
            List list = new ArrayList();
            if (params != null && !params.isEmpty()) {
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    list.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity =
                        new UrlEncodedFormEntity(list, "utf-8");
                post.setEntity(urlEncodedFormEntity);
            }
            if (headers != null && !headers.isEmpty()) {
                Set<String> keySet = headers.keySet();
                for (String s : keySet) {
                    post.addHeader(s, headers.get(s).toString());
                }
            }
            try {
                CloseableHttpResponse response = client.execute(post);
                HttpEntity responseEntity = response.getEntity();
                responseString = EntityUtils.toString(responseEntity, "utf-8");
                jsonResult = JSONObject.parseObject(responseString);
            } catch (JSONException e) {
//                e.printStackTrace();
                jsonResult.put("content", responseString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    public static JSONObject doPostJson(String url, String params) {
        JSONObject result = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        if (StringUtils.isNotEmpty(params)) {
            StringEntity stringEntity = new StringEntity(params, "utf-8");
            httpPost.setEntity(stringEntity);
        }
//        if (StringUtils.isNotEmpty(headers)) {
//            httpPost.setHeader("Content-Type", "application/json");
//        }
        httpPost.setHeader("Content-Type", "application/json");
        try {
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String responseString = EntityUtils.toString(responseEntity, "utf-8");
            result = JSONObject.parseObject(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static JSONObject doPostJson(String url, String params, Map<String, Object> headers) {
        JSONObject result = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        if (StringUtils.isNotEmpty(params)) {
            StringEntity stringEntity = new StringEntity(params, "utf-8");
            httpPost.setEntity(stringEntity);
        }
        if (headers != null && !headers.isEmpty()) {
            Set<String> keySet = headers.keySet();
            for (String s : keySet) {
                httpPost.addHeader(s, headers.get(s).toString());
            }
        }
        try {
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String responseString = EntityUtils.toString(responseEntity, "utf-8");
            result = JSONObject.parseObject(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String url = "http://passportapi-qa.liangkebang.net/user/login/fastV1";
        String phoneNo = "13712345678:0000";
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] textByte = phoneNo.getBytes("UTF-8");
        String phoneNoBase64 = encoder.encodeToString(textByte);
        Map<String, Object> headers = new HashMap<>();
        Map<String, Object> formData = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Authorization", "Verification " + phoneNoBase64);
        formData.put("channelId", 1);
        formData.put("createdFrom", 1);
        formData.put("key", "xyqb");
        formData.put("btRegisterChannelId", "");
        formData.put("dimension", "");
        formData.put("click_id", "");
        JSONObject result = doPost(url, formData, headers);
        System.out.println(result);
        System.out.println(result.get("data"));
    }

}
