package cn.iocoder.yudao.module.iot.framework.util;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.iot.controller.admin.device.vo.DevicePageReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.device.DeviceDO;
import cn.iocoder.yudao.module.iot.dal.mysql.device.DeviceMapper;
import cn.iocoder.yudao.module.iot.framework.constant.Constants;
import cn.iocoder.yudao.module.iot.framework.constant.DeviceStatusEnum;
import cn.iocoder.yudao.module.iot.service.device.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时检查设备mqtt消息是否离线，离线定义为默认时间内没有新消息
 *
 * @author j-sentinel
 */
@Component
@Slf4j
public class CheckDeviceOfflineJob implements JobHandler {

    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private DeviceService deviceService;

    @Override
    @TenantIgnore
    public String execute(String param) {
        DevicePageReqVO respVO = new DevicePageReqVO().setStatus(DeviceStatusEnum.在线.getValue()).setIsEnable(true);
        List<DeviceDO> deviceList = deviceService.selectList(respVO);
        int count = 0;
        for (DeviceDO device : deviceList) {
            if(device.getLastOnlineTime()==null){
                device.setStatus(DeviceStatusEnum.离线.getValue());
                deviceMapper.updateById(device);
                count++;
            }else {
                Duration duration = Duration.between(device.getLastOnlineTime(), LocalDateTime.now());
                //long seconds = duration.getSeconds();
                long millis = duration.toMillis();
                long second = device.getOffLineDuration()==null? Constants.DEVICE_OFFLINE_SECOND : device.getOffLineDuration();
                if(millis > second*1000){//认为设备已经离线
                    device.setStatus(DeviceStatusEnum.离线.getValue());
                    deviceMapper.updateById(device);
                    count++;
                }
            }
        }
        log.info("[job execute][定时检查设备mqtt消息是否离线,数量 ({}) 个]", count);
        return String.format("定时检查设备mqtt消息是否离线,数量 %s 个", count);
    }

}
