package com.zehong.quartz.task;

import com.zehong.common.core.redis.RedisCache;
import com.zehong.system.domain.TDeviceAlarmInfo;
import com.zehong.system.service.ITDeviceAlarmInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * @author geng
 * 订阅事件job
 */

@Component("subscriptEventTask")
public class SubscriptEventTask {

    private Logger logger = LoggerFactory.getLogger(SubscriptEventTask.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ITDeviceAlarmInfoService tDeviceAlarmInfoService;

    /**
     *  自动消警
     */
    public void automaticAlarmElimination(){
        try {
            logger.info("--------------- 自动消警开始 -------------");
            //获取缓存信息
            Map<String,TDeviceAlarmInfo> tDeviceAlarmInfoCache = redisCache.getCacheObject("dangrousSubsciription");
            Iterator<Map.Entry<String, TDeviceAlarmInfo>> it = tDeviceAlarmInfoCache.entrySet().iterator();
            boolean hasEndAlarm = false;
            while(it.hasNext()){
                TDeviceAlarmInfo alarmInfo = it.next().getValue();
                Date day=new Date();
                long timeSpace = (day.getTime() - alarmInfo.getAlarmBeginTime().getTime()) /(60 * 1000) ;
                if(timeSpace > 5){
                    TDeviceAlarmInfo alarm = tDeviceAlarmInfoService.selectTDeviceAlarmInfoById(alarmInfo.getAlarmId());
                    if("0".equals(alarm.getAlarmStatus())){
                        //更新报警结束时间
                        alarmInfo.setAlarmEndTime(new Date());
                        alarmInfo.setAlarmStatus("1");
                        tDeviceAlarmInfoService.updateTDeviceAlarmInfo(alarmInfo);
                    }
                    //清除缓存
                    it.remove();
                    hasEndAlarm = true;
                }
            }
            if(hasEndAlarm){
                redisCache.setCacheObject("dangrousSubsciription",tDeviceAlarmInfoCache);
            }

        }catch (Exception e){
            logger.error("自动消警开始失败：" + e);
        }
    }
}
