package com.zfire.jiasm.syncdata.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zfire.jiasm.syncdata.exception.RemoteServiceException;
import okhttp3.*;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;


public class HttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String requestPostBody(String url, String json, Map<String, String> heads) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        for(String str : heads.keySet()){
            headers.set(str,heads.get(str));
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> httpEntity = new HttpEntity<>(json, headers);

        //获取返回数据
        try {
            String body = restTemplate.postForObject(url, httpEntity, String.class);
            return body;
        }catch(Exception e){
            throw new RemoteServiceException(e.getMessage());
        }
    }


    static private Request.Builder getBodyBuilder(String url, String json, Map<String, String> heads) {
        logger.info("requestPostBody url:" + url);
        logger.info("body:" + json);
        okhttp3.MediaType JSONType = okhttp3.MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSONType, json);
        Request.Builder builder = new Request.Builder();

        builder.url(url);

        if (heads != null) {
            for (String key : heads.keySet()) {

                builder.addHeader(key, heads.get(key));
            }
        }
        builder.post(body);
        return builder;
    }

    static public String requestPostBodyIO(String url, String json, Map<String, String> heads) throws  IOException {
        Request.Builder builder = getBodyBuilder(url,json,heads);
        Request req = builder.build();
        Response response = OkHttpUtil.execute(req);
        logger.error(response.toString());
        return response.body().string();
    }

    static private Request.Builder getGetBuilder(String url, Map<String, String> params, Map<String, String> heads) {
        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();

        if (params != null) {
            for (String key : params.keySet()) {
                urlBuilder.addQueryParameter(key, params.get(key));
            }
        }


        reqBuild.url(urlBuilder.build());
        if (heads != null) {
            for (String key : heads.keySet()) {
                reqBuild.addHeader(key, heads.get(key));
            }
        }

        return reqBuild;
    }

    static public String requestGet(String url, Map<String, String> params, Map<String, String> heads) throws RemoteServiceException {
        Request.Builder reqBuild = getGetBuilder(url, params, heads);
        Request req = reqBuild.build();

        try {
            Response response = OkHttpUtil.execute(req);
            //判断请求是否成功
            if (response.isSuccessful()) {
                String content = response.body().string();
                return content;
                //打印服务端返回结果
            } else {
                throw new RemoteServiceException(response.code(), response.message());
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(HttpUtils.class.getName(), e);
            throw new RemoteServiceException(505, e.getMessage());
        }
    }

    public static String requestPostBodyt(String url, String json, Map<String, String> heads) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("multipart/form-data"));

        for(String str : heads.keySet()){
            headers.set(str,heads.get(str));
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> httpEntity = new HttpEntity<>(json, headers);

        //获取返回数据
        try {
            String body = restTemplate.postForObject(url, httpEntity, String.class);
            return body;
        }catch(Exception e){
            throw new RemoteServiceException(e.getMessage());
        }
    }

    public static String sendData(String url, String content) {
        CloseableHttpClient httpClient;
        HttpPost httpPost = null;
        org.apache.http.HttpEntity entity;
        long interval = System.currentTimeMillis();
        String resStr="";
        JSONObject json = new JSONObject();
        try {
            httpClient = HttpClients.createDefault();
            if (httpClient == null) {
                throw new Exception("httpClient create failed");
            }

            httpPost = new HttpPost(url);
            RequestConfig reqconfig = RequestConfig.custom()
                    .setConnectTimeout(60 * 1000)
                    .setConnectionRequestTimeout(60 * 1000)
                    .setSocketTimeout(60 * 1000).build();
            httpPost.setConfig(reqconfig);
            httpPost.setHeader("Content-Type", "multipart/form-data");
            httpPost.setEntity(new StringEntity(content, "UTF-8"));

            //CloseableHttpResponse res = httpClient.execute(httpPost);
            //int status = res.getStatusLine().getStatusCode();
            CloseableHttpResponse response =  httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            entity = response.getEntity();
            resStr = EntityUtils.toString(entity).trim();
            EntityUtils.consume(entity);
            response.close();
            if (status != HttpStatus.SC_OK) {
                json.put("respCode","faile");
                json.put("respDesc","网络状态异常A");

                resStr=JSON.toJSON(json.toJSONString()).toString();
            }
        } catch (HttpHostConnectException ex) {
            json.put("respCode","faile");
            json.put("respDesc","请求异常B");
            resStr=JSON.toJSON(json.toJSONString()).toString();
        } catch (Exception ex) {
            json.put("respCode","faile");
            json.put("respDesc","请求异常C");
            resStr=JSON.toJSON(json.toJSONString()).toString();
        } finally {
            interval = System.currentTimeMillis() - interval;
            if (httpPost != null)
                httpPost.releaseConnection();
            return resStr;
        }
    }


    static public String requestXwww(String url, MultiValueMap<String, String> forms) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        RestTemplate restTemplate=new RestTemplate();
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(forms, headers);

        //获取返回数据
        String body = restTemplate.postForObject(url, httpEntity, String.class);
        return body;
    }

    static public String requestXww(String url, MultiValueMap<String, String> forms) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(MediaType.MULTIPART_FORM_DATA_VALUE));
        RestTemplate restTemplate=new RestTemplate();
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(forms, headers);

        //获取返回数据
        String body = restTemplate.postForObject(url, httpEntity, String.class);
        return body;

    }

    static public String requestPostForm(String url, Map<String, String> params, Map<String, String> heads) throws RemoteServiceException {

        Request.Builder builder = getFormBuilder(url,params,heads);

        Request req = builder.build();

        try {
            Response response = OkHttpUtil.execute(req);
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new RemoteServiceException(response.code(), response.message());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RemoteServiceException(505, e.getMessage());
        }
    }



    static private Request.Builder getFormBuilder(String url, Map<String, String> params, Map<String, String> heads) {
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        try {
            if (params != null) {
                for (String key : params.keySet()) {
                    if (StringUtils.isNotEmpty(params.get(key))) {
                        bodyBuilder.add(key, params.get(key));
                    } else {
                        bodyBuilder.add(key, "");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

        RequestBody body = bodyBuilder.build();
        Request.Builder builder = new Request.Builder();

        if (heads != null) {
            for (String key : heads.keySet()) {

                builder.addHeader(key, heads.get(key));
            }
        }
        builder.url(url);
        builder.post(body);

        return builder;

    }




}
