package com.bs.data.util;

import cn.hutool.json.JSONUtil;
import com.bs.framework.web.domain.server.Sys;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class DaChengUtil {

    static String uri = "https://iot.zzdacheng.com/api/v1/";
    static String AppId = "2aANnCHx8ickw4kw";
    static String AppSecret = "szQ4DaB5ddRnQBi8T8pcNt2x";
    public static Map<String, String> createSignHeaders(String jsonString, String xClientId, String secureKey) {
        //时间戳
        String xTimestamp = String.valueOf(System.currentTimeMillis());

        MessageDigest digest = DigestUtils.getMd5Digest();
        digest.update(jsonString.getBytes());
        digest.update(xTimestamp.getBytes());
        digest.update(secureKey.getBytes());

        Map<String, String> headers = new HashMap<>();
        headers.put("X-Sign", Hex.encodeHexString(digest.digest()));
        headers.put("X-Client-Id", xClientId);
        headers.put("X-Timestamp", xTimestamp);

        return headers;
    }

    public static Map<String, Object> sendPost(String method, Map<String, String> headerMap, Map<String, Object> param) {
        Map<String, Object> ret = new HashMap<>();
        try {
            URL url = new URL(uri + method);
            // 要请求的URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法（POST）
            connection.setRequestMethod("POST");
            // 设置请求头
            //Map<String, String> headers = new HashMap<>();
            headerMap.put("Content-Type", "application/json; utf-8");
            headerMap.put("Accept", "application/json");
            // 可以根据需要添加更多请求头
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            // 将Map转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonBody = objectMapper.writeValueAsString(param);
            // 允许输出（发送请求体）
            connection.setDoOutput(true);
            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // 处理响应体
            if (responseCode == HttpURLConnection.HTTP_OK) { // 200
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    // 假设响应体也是JSON格式，我们可以将其解析为Map
                    ret = objectMapper.readValue(response.toString(), Map.class);
                    // 打印响应体
                    //System.out.println("Response Body: " + ret);
                    //System.out.println(ret.get("result"));
                    return ret;
                }
            } else {
                // 处理错误响应
                System.err.println("Request failed with response code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static Map<String, Object> sendGet(String method, Map<String, String> headerMap, Map<String, Object> param) {
        Map<String, Object> ret = new HashMap<>();
        try {
            // 将Map转换为URL查询参数字符串
            String queryParams = param.entrySet().stream()
                    .map(entry -> {
                        try {
                            return URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()) + "=" +
                                    URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8.toString());
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                    })
                    .collect(Collectors.joining("&"));
            String urlString = uri + method + "?" + queryParams;
            URL url = new URL(urlString);
            // 要请求的URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法（POST）
            connection.setRequestMethod("GET");
            // 设置请求头
            //Map<String, String> headers = new HashMap<>();
            headerMap.put("Content-Type", "application/json; utf-8");
            headerMap.put("Accept", "application/json");
            // 可以根据需要添加更多请求头
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            ObjectMapper objectMapper = new ObjectMapper();
            // 处理响应体
            if (responseCode == HttpURLConnection.HTTP_OK) { // 200
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    // 假设响应体也是JSON格式，我们可以将其解析为Map
                    ret = objectMapper.readValue(response.toString(), Map.class);
                    // 打印响应体
                    //System.out.println("Response Body: " + ret);
                    //System.out.println(ret.get("result"));
                    return ret;
                }
            } else {
                // 处理错误响应
                System.err.println("Request failed with response code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static String getToken() {
        //https://md5jiami.bmcx.com/
        Map<String, Object> paramLogin = new HashMap<>();
        paramLogin.put("expires", 7200);

        Map<String, String> headerMap = createSignHeaders(JSONUtil.toJsonStr(paramLogin), AppId, AppSecret);
        System.out.println(JSONUtil.toJsonStr(headerMap));

        Map<String, Object> ret = sendPost("token", headerMap, paramLogin);
        return ret.get("result").toString();
    }

    public static String getProduct(String token, int pageIndex, int pageSize) {
        Map<String, String> headParam = new HashMap<>();
        headParam.put("X-Access-Token", token);

        Map<String, Object> param = new HashMap<>();
        param.put("pageIndex", pageIndex);
        param.put("pageSize", pageSize);

        Map<String, Object> ret = sendGet("product/_detail/_query/page", headParam, param);
        return ret.get("result").toString();
    }

    public static String getAllProduct(String token) {
        Map<String, String> headParam = new HashMap<>();
        headParam.put("X-Access-Token", token);

        Map<String, Object> param = new HashMap<>();

        Map<String, Object> ret = sendGet("product/_detail/_query/list", headParam, param);
        return ret.get("result").toString();
    }

    public static String getDevice(String token, int pageIndex, int pageSize) {
        Map<String, String> headParam = new HashMap<>();
        headParam.put("X-Access-Token", token);

        Map<String, Object> param = new HashMap<>();
        param.put("pageIndex", pageIndex);
        param.put("pageSize", pageSize);

        Map<String, Object> ret = sendGet("device/_detail/_query/page", headParam, param);
        return ret.get("result").toString();
    }

    public static String getAllDevice(String token) {
        Map<String, String> headParam = new HashMap<>();
        headParam.put("X-Access-Token", token);

        Map<String, Object> param = new HashMap<>();

        Map<String, Object> ret = sendGet("device/_detail/_query/list", headParam, param);
        return ret.get("result").toString();
    }

    public static void main(String[] args) {
        String token = getToken();
        //String result = getAllProduct(token);
        String result = getAllDevice(token);
        System.out.println(result);
    }
}
