package com.iformall.schedule;

import com.iformall.domain.po.WxDevice;

import com.iformall.enums.EnumDeviceOnlineStatus;
import com.iformall.enums.EnumDeviceStatus;
import com.iformall.mapper.WxDeviceMapper;

import com.iformall.service.WxDeviceService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


@Component
public class DeviceHbCheckSchedule {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final int TIME_OUT_VALUE = 15 * 60 * 1000; //15分钟


    @Autowired
    WxDeviceMapper wxDeviceMapper;

    @Scheduled(cron = "0 */5 * * * *?") // 每5分钟检查一次
    //@Scheduled(cron = "*/10 * * * * ?") // 测试10秒中一次
    public void deviceHbCheckSchedule() {

        WxDevice wxDevice = new WxDevice();
        wxDevice.setStatus(EnumDeviceStatus.VALID.getCode());
        List<WxDevice> list = wxDeviceMapper.findList(wxDevice);

        list.stream().forEach(d->{
            WxDevice record = new WxDevice();
            record.setId(d.getId());

            if (d.getLastHbTime() == null) {
                record.setOnlineStatus(EnumDeviceOnlineStatus.OFFLINE.getCode());
            } else {
                if (new Date().getTime() - d.getLastHbTime().getTime() > TIME_OUT_VALUE) {
                    record.setOnlineStatus(EnumDeviceOnlineStatus.OFFLINE.getCode());
                } else {
                    record.setOnlineStatus(EnumDeviceOnlineStatus.ONLINE.getCode());
                }
            }
            if (!d.getOnlineStatus().equals(record.getOnlineStatus())) {
                wxDeviceMapper.updateByPrimaryKeySelective(record);
            }
        });
    }

}