package com.bonus.sgzb.common.core.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.sgzb.common.core.constant.HttpStatus;
import com.bonus.sgzb.common.core.constant.UserConstants;
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.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpHelper {

    public static String sendHttpPost(String url, String JSONBody) throws Exception {
        System.out.println("JSONBody-=========:" + JSONBody);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.setEntity(new StringEntity(JSONBody,StandardCharsets.UTF_8));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        response.close();
        httpClient.close();
        return responseContent;
    }

    public static String sendHttpPost(String url,String token,String content,String intelligentAppKey) throws Exception {
        System.out.println("JSONBody-=========:" + content);
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(url);
            post.setHeader("token", token);
            post.setHeader("appKey", intelligentAppKey);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("params", content.getBytes());
            post.setEntity(builder.build());

            CloseableHttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            response.close();
            return responseContent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String doPost(String urlString,String param) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(urlString);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

    public static String getIotToken() {
        Map<String,Object> map=new HashMap<>();
        String redisCode = null;
        map.put("type", UserConstants.IOT_TYPE);
        map.put("from",UserConstants.IOT_FROM);
        map.put("username",UserConstants.IOT_USERNAME);
        //采用md5加密
        map.put("password",UserConstants.IOT_PASSWORD);
        String param = JSON.toJSONString(map);
        String resultUser = HttpHelper.doPost(HttpStatus.LOGIN_URL,param);
        if (resultUser == null){
            throw new RuntimeException("返回数据为空！！");
        }
        JSONObject object = JSONObject.parseObject(resultUser);
        if ("0".equals(object.getString("status"))){
            redisCode = object.getString("token");
        }else {
            throw new RuntimeException("返回数据为空！！");
        }
        return redisCode;
    }


}