package com.tykj.dev.rfid.timeTask;

import com.tykj.dev.config.TaskBeanConfig;
import com.tykj.dev.rfid.entity.domin.InputOutputDevice;
import com.tykj.dev.rfid.repository.InputOutputDeviceDao;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.ScheduledFuture;

/**
 * @author dengdiyi
 */
@Slf4j
@Component
@EnableAsync
@Data
public class AccessSchedulerTask {

    /**
     * 每分钟
     */
    private String cron = "0 0/1 * * * ?";

    /**
     * 门禁白名单过期时间（1分钟（毫秒））
     */
    private long overTime = 60_000;

    private ScheduledFuture scheduledFuture;

    final InputOutputDeviceDao inputOutputDeviceDao;

    public AccessSchedulerTask(InputOutputDeviceDao inputOutputDeviceDao){
        this.inputOutputDeviceDao = inputOutputDeviceDao;
        scheduledFuture = TaskBeanConfig.getThreadPoolTaskScheduler().schedule(new AccessDeleteTask(), triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext));
        log.info("[门禁模块]:定时删除白名单任务执行了");
    }

    public class AccessDeleteTask implements Runnable {
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void run() {
            if (inputOutputDeviceDao!=null){
                List<InputOutputDevice> inputOutputDevices = inputOutputDeviceDao.findAllByIsRead(1);
                if (inputOutputDevices.size()>0){
                    inputOutputDevices.forEach(inputOutputDevice -> {
                        long time = System.currentTimeMillis()-inputOutputDevice.getUpdateTime().getTime();
                        if (time>overTime){
                            inputOutputDeviceDao.deleteById(inputOutputDevice.getId());
                            log.info("[门禁模块]:删除了id为"+inputOutputDevice.getDeviceId()+"装备的白名单");
                        }
                    });
                }
            }
        }
    }
}
