package com.wsm.admin.device.init;

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

import com.wsm.admin.constant.MsgCode;
import com.wsm.admin.model.Device;
import com.wsm.admin.model.DeviceEvent;
import com.wsm.admin.service.IDeviceEventService;
import com.wsm.admin.service.IDeviceService;
import com.wsm.common.util.RedisUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/**
 * Created by owen on 2018/8/24.
 *
 * 定时任务，检测设备状态
 */

@Component
public class TaskSchedule {

    /** The logger. */
    private Logger logger = Logger.getLogger(TaskSchedule.class);

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IDeviceEventService deviceEventService;


    /**
     * 每天1点检查未开始的活动
     * 每天24点执行一次  @Scheduled(cron=" 0 0 0 * * ? ") @Scheduled(cron=" * 1  * * ? ")
     *
     * Scheduled(cron=" 10 0/5 * * * ? ")   //每五分钟执行一次
     */
    @Scheduled(cron=" 0 0 1 * * ? ")
//    @Scheduled(cron=" 10 0/5 * * * ? ")
    public void checkDeviceId(){
        logger.info("run checkDeviceId");

        List<Device> list = deviceService.findAll();

        for (Device d : list) {
            boolean b = redisUtil.hasKey(d.getDeviceId());
            // 如果不存在
            if (!b) {
                logger.info("离线设备号：" + d.getDeviceId());

                // 设备离线，如果有离线设备事件没有处理，就更新时间，让它置顶。若没有，就创建一个事件. 3:故障

                DeviceEvent event = deviceEventService.findByStatusAndDeviceId(d.getId(), 3);
                if (event == null) {
                    event = new DeviceEvent();
                    event.setCreateTime(new Date());
                    event.setDevice(d);
                    event.setPostTime(new Date());
                    // 事件异常状态: 0-正常  1-报警  2-低压  3-故障
                    event.setStatus(3);
                    // 处理状态：0-待解决, 1-已立案，2-出警中，3-已解决
                    event.setHandleStatus((byte)0);
                    event.setContent("设备离线");
                }

                event.setUpdateTime(new Date());
                deviceEventService.save(event);

                //修改设备状态
                // 3:故障
                d.setStatus((byte)3);
                d.setUpdateTime(new Date());
                deviceService.update(d);
                redisUtil.delete(MsgCode.REDIS_CYCLE_DEVICE_LIST);


            }

        }
        logger.info("end checkDeviceId");


    }


}
