package net.northking.cctp.executePlan.consumer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import net.northking.cctp.executePlan.api.service.AtuPlanBatchApiService;
import net.northking.cctp.executePlan.constants.RabbitConstant;
import net.northking.cctp.executePlan.db.entity.AtuPlanBatchDeviceLink;
import net.northking.cctp.executePlan.db.service.AtuPlanBatchDeviceLinkService;
import net.northking.cctp.executePlan.dto.planBatch.DeviceOfflineMsgDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Title: DeviceOfflineConsumer</p>
 * <p>Description: </p>
 *
 * @Author chenjianfeng
 * @Version V1.0
 * @Date 2022/12/24
 * <p>Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.</p>
 */
@Component
public class DeviceOfflineConsumer {

    private final static Logger logger = LoggerFactory.getLogger(DeviceOfflineConsumer.class);

    @Autowired
    private AtuPlanBatchDeviceLinkService planBatchDeviceLinkService;

    @Autowired
    private AtuPlanBatchApiService planBatchApiService;

    @RabbitListener(queues = RabbitConstant.DEVICE_OFFLINE_QUEUE)
    public void receive(Message message){
        try {
            logger.info("设备离线消息 ==> " + new String(message.getBody()));
            JSONObject event = JSONUtil.parseObj(new String(message.getBody()));
            DeviceOfflineMsgDto deviceOfflineMsgDto = JSONUtil.toBean(event, DeviceOfflineMsgDto.class);

            // 查询该设备绑定的未完成的批次
            logger.debug("查询该设备绑定的未完成的批次");
            List<AtuPlanBatchDeviceLink> batchDeviceLinkList =
                    planBatchDeviceLinkService.queryByOfflineDeviceId(deviceOfflineMsgDto.getDeviceId());
            logger.debug("未完成的批次数量 => " + batchDeviceLinkList.size());
            if (CollUtil.isEmpty(batchDeviceLinkList)) {
                return;
            }
            logger.debug("更新批次中该设备为离线");
            for (AtuPlanBatchDeviceLink batchDeviceLink : batchDeviceLinkList) {
                // 更新批次绑定的设备为离线，更新离线时间
                batchDeviceLink.setOffline(true);
                batchDeviceLink.setOfflineTime(deviceOfflineMsgDto.getLastHeartbeatTime());
                planBatchDeviceLinkService.updateByPrimaryKey(batchDeviceLink);
            }
            List<String> batchIdList = batchDeviceLinkList.stream().map(AtuPlanBatchDeviceLink::getBatchId)
                    .collect(Collectors.toList());
            logger.debug("包含该离线设备的批次集合 => " + JSONUtil.toJsonStr(batchIdList));

            long lastOfflineTime = deviceOfflineMsgDto.getLastHeartbeatTime().getTime();
            // 判断批次的所有设备是否都离线超过20分钟
            for (String batchId : batchIdList) {
                planBatchApiService.processBatchTaskTimeout(batchId, lastOfflineTime);
            }
        }catch (Exception e){
            logger.error("离线消息处理异常", e);
        }
    }
}
