package com.jjt.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * IotTools$
 *
 * @author wukai
 * @date 2024/5/20 17:37
 */
@Slf4j
public class IotTools {
    /**
     * 获取接口返回值
     * 如果报错，则一直重试
     *
     * @param request request
     * @return json
     */
    public static JSONObject getData(HttpRequest request) {
        //连接超时时间 5秒
        request.setConnectionTimeout(5000);
        HttpResponse execute;
        int times = 1;
        while (true) {
            try {
                // 尝试执行的操作
                execute = response(request);
                // 如果操作成功，则不会执行以下代码
                break; // 退出循环
            } catch (Exception e) {
                e.printStackTrace();
                log.error("接口返回数据失败，正在第{}次重新请求！！！,请求体：{}", times++,request);
                if (times > 5) {
                    log.error("重新5次未获取到数据！！！");
                    throw new RuntimeException("重试5次未获取到数据！！！");
                }
                try {
                    Thread.sleep(500);
                    //暂停0.5秒一直重试
                } catch (InterruptedException ignored) {
                }
            }
        }
        String res = new String(execute.body().getBytes(), StandardCharsets.UTF_8);
        return JSONUtil.parseObj(res, true);
    }

    public static HttpResponse response(HttpRequest request) throws Exception {
        try (HttpResponse res = request.execute()) {
            if (!res.isOk()) {
                throw new RuntimeException(res.body());
            }
            return res;
        }
    }
}
