package com.reyun.saas.mob.user.task;

import com.reyun.saas.mob.user.dao.WarningConfigMapper;
import com.reyun.saas.mob.user.domain.WarningConfig;
import com.reyun.saas.mob.user.dto.WarningConfigDTO;
import com.reyun.saas.mob.user.thread.warning.WarningThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @desc 预警配置检测
 */
@Slf4j
@Component
public class WarningConfigTask {

    @Autowired
    @Qualifier("warningThreadPool")
    private ThreadPoolTaskExecutor warningThreadPool;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private WarningConfigMapper warningConfigMapper;

    @Async
    @Scheduled(cron = "0 0 * * * ? ")//整点
    public void checkWarningReport(){
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("checkWarningReport", "lock", 10, TimeUnit.SECONDS);
        if (!lock) {
            log.info("另一台服务正在预警监测中.......");
            return;
        }
        Example example = new Example(WarningConfig.class);
        example.and().andEqualTo("isusing",true).andEqualTo("delFlag",false).andEqualTo("template",false);
        List<WarningConfigDTO> warningConfigs = warningConfigMapper.checkWarningReportList();
        for (WarningConfigDTO warningConfig : warningConfigs) {
            warningThreadPool.execute(new WarningThread(warningConfig));
        }
    }
}
