package com.chaozhanggui.admin.system.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * @author admin
 * @date 2021/3/18 14:28
 */
public class HttpUtils extends HttpRequest {
    public HttpUtils(String url) {
        super(url);
    }


    public static String post(String url,String param){
        if(ObjectUtil.isNotEmpty(param)){
            return HttpRequest.post(url).header("Content-type","application/x-www-form-urlencoded").body(param).execute().body();
        }
        return HttpRequest.post(url).header("Content-type","application/x-www-form-urlencoded").execute().body();
    }

    public static String get(String url,String param){
        if(ObjectUtil.isNotEmpty(param)){
            return HttpRequest.get(url).header("Content-type","application/json").body(param).execute().body();
        }
        return HttpRequest.get(url).execute().body();
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }



    private static JSONObject get4GCommonMessageParams() {
        JSONObject params = new JSONObject();
        params.put("appId", "ZF544");
        params.put("timestamp", System.currentTimeMillis());
        String requestId = UUID.randomUUID().toString();
        params.put("requestId", requestId);
        params.put("userCode", "ZF544");
        String signContent = SignUtils.getSignContent1(params, "2022bsjZF544GAH");
        String token = MD5Util.MD5Encode(signContent, "UTF-8").toUpperCase();
        params.put("token", token);
        return params;
    }

    public static  void main(String[] args){
//        JSONObject body= get4GCommonMessageParams();
//
////        body.put("devName", "ZF544CG02S00001");
////        body.put("cloudType","2");
////        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://ioe.car900.com/v1/openApi/dev/registerCloud.json");
////        body.forEach((s, o) -> {
////            try {
////                builder.queryParam(s, URLEncoder.encode(o.toString(), "UTF-8"));
////            } catch (UnsupportedEncodingException e) {
////                e.printStackTrace();
////            }
////        });
////        UriComponents uriComponents = builder.build(true);
////        String response =new  RestTemplate().getForObject(uriComponents.toUri(), String.class);
////        System.out.println(response);
//
//
//         body= get4GCommonMessageParams();
//        body.put("devName", "ZF544CG02S00001");
//        body.put("biz_type", "2");
//        body.put("money", "哈哈哈哈哈哈哈哈哈哈");
//        body.put("content","哈哈哈哈哈哈哈哈哈哈");
//        body.put("broadCastType", "16");
//
//
////        System.out.println(sendGet("https://ioe.car900.com/v1/openApi/dev/controlDevice.json",body.toJSONString()));
//
//
//        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://ioe.car900.com/v1/openApi/dev/controlDevice.json");
//        body.forEach((s, o) -> {
//            try {
//                builder.queryParam(s, URLEncoder.encode(o.toString(), "UTF-8"));
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        });
//        UriComponents uriComponents = builder.build(true);
//        String response =new  RestTemplate().getForObject(uriComponents.toUri(), String.class);
//        System.out.println(response);


    }


}
