package com.wteam.framework.modules.hardware;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.wteam.framework.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务，每24小时向硬件注册回调url
 */
@Slf4j
public class RegistrationTask {
    public static void main(String[] args) {
        // 创建一个定时任务执行器
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 接口地址和参数
//        https://xiaofeng.pankzone.com/api/openapi/get_tokenv2.x?mac=863569068849199&pwd=239818&apikey=889a7a889678edfef18fa669def89
        String apiUrl = "https://xiaofeng.pankzone.com/api/openapi/set_dev_callbackv2.x";
        String mac = "863569068849199";
        String url = "http://139.9.38.185:8889/v1/hardware/verification";
        String tk = ApiCallerUtil.callApi();
        log.info("此时获取到的token为：{}", tk);

        // 初始化任务，立即执行一次
        Runnable registrationTask = () -> {
            HttpResponse httpResponse = HttpRequest.post(apiUrl)
                    .form("mac", mac)
                    .form("url", url)
                    .form("tk", tk)
                    .execute();
            String body = httpResponse.body();
            // 解析JSON响应
            JSONObject json = new JSONObject(body);
            // 获取code和token的值
            int code = json.getInt("code");
            if (code != 0) {
                throw new ServiceException("硬件回调url设置接口异常！");
            }
            log.info("此时的响应结果为：{}", json);
        };

        // 每24小时执行一次任务
        long initialDelay = 0; // 初始延迟为0秒，即立即执行
        long period = 24 * 60 * 60; // 24小时，以秒为单位

        // 启动定时任务
        scheduler.scheduleAtFixedRate(registrationTask, initialDelay, period, TimeUnit.SECONDS);
    }
}
