package com.huimv.video.dhicc.util;


import org.apache.commons.collections.MapUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/*****
 * @Author: yangdi  hm
 * @Description: entity
 ****/
public class HttpClient {
    private String url;
    private Map<String, String> param;
    private int statusCode;
    private String content;
    private String xmlParam;
    private boolean isHttps;

    public boolean isHttps() {
        return isHttps;
    }

    public void setHttps(boolean isHttps) {
        this.isHttps = isHttps;
    }

    public String getXmlParam() {
        return xmlParam;
    }

    public void setXmlParam(String xmlParam) {
        this.xmlParam = xmlParam;
    }

    public HttpClient(String url, Map<String, String> param) {
        this.url = url;
        this.param = param;
    }


    public HttpClient(String url) {
        this.url = url;
    }

    public void setParameter(Map<String, String> map) {
        param = map;
    }


    public void addParameter(String key, String value) {
        if (param == null)
            param = new HashMap<String, String>();
        param.put(key, value);
    }


    public void post() throws ClientProtocolException, IOException {
        HttpPost http = new HttpPost(url);
        setEntity(http);
        execute(http);
    }

    public void put() throws ClientProtocolException, IOException {
        HttpPut http = new HttpPut(url);
        setEntity(http);
        execute(http);
    }


    public void get() throws ClientProtocolException, IOException {
        if (param != null) {
            StringBuilder url = new StringBuilder(this.url);
            boolean isFirst = true;
            for (String key : param.keySet()) {
                if (isFirst) {
                    url.append("?");
                } else {
                    url.append("&");
                }
                url.append(key).append("=").append(param.get(key));
            }
            this.url = url.toString();
        }
        HttpGet http = new HttpGet(url);
        execute(http);
    }

    /**
     * set http post,put param
     */
    private void setEntity(HttpEntityEnclosingRequestBase http) {
        if (param != null) {
            List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            for (String key : param.keySet()) {
                nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
            }
            http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
        }
        if (xmlParam != null) {
            http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
        }
    }

    private void execute(HttpUriRequest http) throws ClientProtocolException,
            IOException {
        CloseableHttpClient httpClient = null;
        try {
            if (isHttps) {
                SSLContext sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustStrategy() {
                            // 信任所有
                            @Override
                            public boolean isTrusted(X509Certificate[] chain,
                                                     String authType)
                                    throws CertificateException {
                                return true;
                            }
                        }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sslContext);
                httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                        .build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            CloseableHttpResponse response = httpClient.execute(http);
            try {
                if (response != null) {
                    if (response.getStatusLine() != null) {
                        statusCode = response.getStatusLine().getStatusCode();
                    }
                    HttpEntity entity = response.getEntity();
                    // 响应内容
                    content = EntityUtils.toString(entity, Consts.UTF_8);
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
    }


    public static String httpClientPostSetBody(String url, Map<String, String> parmaMap1) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        builder.setCharset(Charset.forName("utf-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.setCharset(StandardCharsets.UTF_8);
        if (MapUtils.isNotEmpty(parmaMap1)) {
            for (Map.Entry<String, String> entry : parmaMap1.entrySet()) {
                System.out.println(entry.getKey());
                System.out.println(entry.getValue());
                builder.addTextBody(entry.getKey(), entry.getValue(), contentType);
                System.out.println("正在循环");
            }
        }
        System.out.println(builder.toString());
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        // 执行提交
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            // 将响应内容转换为字符串
            result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
        }
        httpClient.close();
        return result;
    }


    public static String httpClientUploadFilePut(String url, Map<String, String> parma1) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";

        HttpPut httpPut = new HttpPut(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //设置文本字符编码为UTF-8
        //中间是格式
        //ContentType contentType= ContentType.create("application/x-www-form-urlencoded", Charset.forName("UTF-8"));
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        builder.setCharset(Charset.forName("utf-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.setCharset(StandardCharsets.UTF_8);
        // 文件流  应该写成可以复用的工具类
        //builder.addBinaryBody("photo",file.getBytes());
        // builder.addBinaryBody(file.getName(), file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getName());// 文件流
        System.out.println("获取文件成功");
        //暂时无法封装成工具

        System.out.println("name=" + parma1.get("name"));
        builder.addTextBody("id", parma1.get("id"), contentType);
        builder.addTextBody("name", parma1.get("name"), contentType);
        builder.addTextBody("mark", parma1.get("mark"), contentType);
        System.out.println(builder.toString());
        HttpEntity entity = builder.build();
        httpPut.setEntity(entity);
        // 执行提交
        HttpResponse response = httpClient.execute(httpPut);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            // 将响应内容转换为字符串
            result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
        }
        httpClient.close();

        return result;
    }


    public static String doDelete(String url) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpDelete.setConfig(requestConfig);
        httpDelete.setHeader("Content-type", "application/json");
        httpDelete.setHeader("DataEncoding", "UTF-8");
        // httpDelete.setHeader("token", token);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpDelete);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    private static CloseableHttpClient buildSSLCloseableHttpClient()
            throws Exception {
        SSLContext sslContext = new org.apache.http.conn.ssl.SSLContextBuilder().loadTrustMaterial(null,
                new TrustStrategy() {
                    // 信任所有
                    public boolean isTrusted(X509Certificate[] chain,
                                             String authType) throws CertificateException {
                        return true;
                    }
                }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, new String[]{"TLSv1.2"}, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }


    public static String httpClientUploadFilePost(String url, MultipartFile file, Map<String, String> header, Map<String, String> parma1) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {

            HttpPost httpPost = new HttpPost(url);
            //请求头,women
          /*  if (MapUtils.isNotEmpty(header)) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            */

            httpPost.setHeader("Authorization", "Bearer 1:0bf83146-2b0a-4dc9-9a61-044875561e75");
            httpPost.setHeader("Connection", "keep-alive");
            httpPost.setHeader("Content-Type", "multipart/form-data");
            // httpPost.setHeader("Host","36.26.62.70");
            // httpPost.setHeader("Content-Length",String.valueOf(file.getSize()));
//            httpPost.setHeader("Accept","*/*");
//            httpPost.setHeader("Accept-Encoding","gzip, deflate, br");
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //设置文本字符编码为UTF-8
            //中间是格式
            //ContentType contentType= ContentType.create("application/x-www-form-urlencoded", Charset.forName("UTF-8"));
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setCharset(StandardCharsets.UTF_8);

            // 文件流  应该写成可以复用的工具类
            // builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getName());
            builder.addBinaryBody(file.getName(), file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getName());// 文件流
            // builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getName());// 文件流
            System.out.println("获取文件成功");
            //暂时无法封装成工具


            HttpEntity entity = builder.build();
            System.out.println("获取文件成功1");
            httpPost.setEntity(entity);
            // 执行提交
            System.out.println("获取文件成功2");

            CloseableHttpClient buildSSLCloseableHttpClient = buildSSLCloseableHttpClient();
            System.setProperty("jsse.enableSNIExtension", "false");

            CloseableHttpResponse response = buildSSLCloseableHttpClient.execute(httpPost);
            System.out.println("获取文件成功3");
            System.out.println(response.toString());
            System.out.println("获取文件成功4");
            HttpEntity responseEntity = response.getEntity();
            System.out.println("fanhui" + responseEntity.getContent().toString());
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }

        } catch (Exception e) {
            System.out.println(e);
            System.out.println("baocuo");
        } finally {
            try {
                httpClient.close();

            } catch (IOException e) {
                System.out.println("baocu");
            }
        }
        return result;
    }


    public int getStatusCode() {
        return statusCode;
    }

    public String getContent() throws ParseException, IOException {
        return content;
    }
}