package com.bcxin.identify.util.baidu;

import com.bcxin.identify.util.common.StringUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * http 工具类
 */
public class BaiduHttpUtil {

    private static final String APPLICATION_JSON = "application/json;charset=utf-8";

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        String result = "";
        DataOutputStream out = null;
        BufferedReader in = null;
        try {
            System.out.println("=======> post url:" + generalUrl);
            System.out.println("=======> post params:" + params);
            URL url = new URL(generalUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // 得到请求的输出流对象
            out = new DataOutputStream(connection.getOutputStream());
            out.write(params.getBytes(encoding));
            out.flush();
            out.close();
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应

            in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), encoding));
            String getLine;
            while ((getLine = in.readLine()) != null) {
                result += getLine;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close(); // 输入流关闭
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close(); // 输出流关闭
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("=======> post result:" + result);
        return result;
    }

    public static String doPost(String url, String token, String json) {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()){
            HttpPost httppost = new HttpPost(url);
            httppost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
            if(StringUtil.isNotEmpty(token)){
                httppost.addHeader("token", token);
            }
            if(StringUtil.isNotEmpty(json)){
                StringEntity se = new StringEntity(json, StandardCharsets.UTF_8);
                se.setContentType(APPLICATION_JSON);
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
                httppost.setEntity(se);
            }
            try (CloseableHttpResponse response = httpclient.execute(httppost) ){
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, StandardCharsets.UTF_8);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
