package com.fuyuanshen.global.queue;// ScheduledTasks.java

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.vo.OnlineStatusVo;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;

@Component
public class OnlineStatusTask {

    @Autowired
    private DeviceMapper deviceMapper;
    // 使用cron表达式，每分钟的第0秒执行
    @Scheduled(cron = "0 */3 * * * ?")
    public void cronTask() {
        List<OnlineStatusVo> onlineStatusVos = deviceMapper.queryOnlineStatusList();
        onlineStatusVos.forEach(item -> {
            String onlineStatusKey = GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX;
            String status = RedisUtils.getCacheObject(onlineStatusKey);
            if(StringUtils.isBlank(status) || "0".equals(status)){
                UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", item.getId());
                updateWrapper.set("online_status", 0);
                deviceMapper.update(updateWrapper);
            }
        });
    }
}
