package com.jpsoft.shinestar.scheduled;

import com.jpsoft.shinestar.modules.base.entity.DeviceInfo;
import com.jpsoft.shinestar.modules.base.service.DeviceInfoService;
import com.jpsoft.shinestar.modules.pacs.service.IGuardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

/**
 * @author 墨鱼_mo
 * @date 2020-3-25 11:11
 */
@Component
@Slf4j
@Profile(value = {"production","test"})
public class HeartbeatDetectionTask {

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private IGuardService guardService;

    //每2分钟执行一次->同时在unactive方法中执行
    @Scheduled(cron = "0 0/2 * * * ?")
    public void run() {
        log.warn("设备在线定时任务启动");
        List<DeviceInfo> deviceInfoList = deviceInfoService.listOnline();

        if (deviceInfoList.size() > 0) {
            for (DeviceInfo deviceInfo : deviceInfoList) {
                if (deviceInfo.getHeartbeatUpdateTime() != null) {
                    Long heartbeatUpdateTime = deviceInfo.getHeartbeatUpdateTime().getTime();
                    Date now = new Date();

                    //超过5分钟没有心跳信号
                    if (now.getTime() - heartbeatUpdateTime > 5 * 60 * 1000) {
                        try {
                            Boolean isKeepAlive = guardService.keepAlive(deviceInfo.getId());

                            if (isKeepAlive) {
                                if("1".equals(deviceInfo.getManufacturer())){
                                    deviceInfo.setAbnormalReason("宇视设备可正常访问，但无心跳返回，请查看设备服务器配置");
                                }
                                else{
                                    //海康设备能正常返回网络信息就算正常
                                    deviceInfo.setHeartbeatUpdateTime(new Date());
                                }
                            } else {
                                deviceInfo.setAbnormalReason("设备离线");
                                deviceInfo.setIsOnline(false);
                            }

                            deviceInfo.setUpdateTime(new Date());
                            deviceInfoService.update(deviceInfo);
                        } catch (Exception e) {
                            deviceInfo.setAbnormalReason("设备离线," + e.getMessage());
                            deviceInfo.setIsOnline(false);
                            deviceInfo.setUpdateTime(new Date());

                            deviceInfoService.update(deviceInfo);
                        }
                    }
                }
            }
        }

        log.warn("设备在线定时任务结束");
    }
}
