package com.ruoyi.task.device;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.bst.device.domain.Device;
import com.ruoyi.bst.device.domain.DeviceQuery;
import com.ruoyi.bst.device.service.DeviceIotService;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.bst.device.utils.DeviceUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.iot.service.impl.DeviceOnlineStatus;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class DeviceTask {

    @Autowired
    private DeviceIotService deviceIotService;

    @Autowired
    private DeviceService deviceService;

    // 监控所有设备
    public void monitorAll() {
        deviceIotService.monitor(new ArrayList<>());
    }

    /**
     * 将过久未上报数据的设备设置为离线
     */
    public void monitorOffline(Integer seconds) {
        // 条件：在线且最后上报时间小于当前时间 - seconds秒
        DeviceQuery query = new DeviceQuery();
        query.setOnlineStatus(DeviceOnlineStatus.ONLINE.getStatus());
        query.setLastTimeEnd(LocalDateTime.now().plusSeconds(-seconds));

        Device data = new Device();
        data.setOnlineStatus(DeviceOnlineStatus.OFFLINE.getStatus());
        int update = deviceService.updateByQuerySimple(data, query);
        log.info("更新了{}条离线的设备数据", update);
    }

    public void refreshIot() {
        // 获取全部设备MAC
        List<String> macList = deviceService.selectAllMac();
        if (CollectionUtils.isEmptyElement(macList)) {
            return;
        }
        List<Device> deviceList = new ArrayList<>();
        for (String mac : macList) {
            if (StringUtils.isBlank(mac)) {
                continue;
            }
            Device device = new Device();
            device.setMac(mac);
            Map<String, Object> info = deviceIotService.getIotInfo(mac);
            if (info == null) {
                continue;
            }
            DeviceUtil.setIotInfo(device, info);
            deviceList.add(device);
        }

        if (CollectionUtils.isEmptyElement(deviceList)) {
            return;
        }
        int rows = deviceService.batchUpdateIot(deviceList);
        log.info("更新了{}条设备数据", rows);
    }

}
