package com.multictrl.common.task;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.multictrl.common.constant.BusinessConstant;
import com.multictrl.common.utils.CacheUtils;
import com.multictrl.modules.business.service.MqttPushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * DRC心跳任务
 *
 * @author Sdy
 * @since 1.0.0 2026/4/27
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DrcHeartbeat {
    private final MqttPushService mqttPushService;

    @Scheduled(fixedRate = 10 * 1000)
    public void drcHeartBeat() {
        List<String> dockSnList = Optional.ofNullable(CacheUtils.get(BusinessConstant.DRC_HEART_BEAT_SN))
                .filter(obj -> obj instanceof List)
                .map(obj -> (List<String>) obj)
                .orElse(Collections.emptyList());
        log.info("drc-->{}, HeartBeat", dockSnList);
        for (String dockSn : dockSnList) {
            String topic = "thing/product/" + dockSn + "/drc/down";
            JSONObject message = new JSONObject();
            message.set("timestamp", System.currentTimeMillis());
            message.set("method", "heart_beat");
            //适配机场1
            message.set("seq", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.set("timestamp", System.currentTimeMillis());
            message.set("data", data);
            mqttPushService.pushMessageByClient2(topic, message.toString());
            log.info("drc-->{}, HeartBeat topic:{}, data:{}", dockSn, topic, data);
        }
    }
}
