package com.yeejoin.amos.patrol.schedule;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.patrol.business.service.intfc.ILatentDangerService;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 隐患定时任务
 */
@Configuration("latentDanerScheduled")
@EnableScheduling
public class LatentDanerScheduled {

    @Autowired
    private ILatentDangerService iLatentDangerService;
    @Autowired(required = false)
    org.redisson.api.RedissonClient redisson;

    @Value("${spring.redis.mode}")
    private String cluster;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 每1分钟执行一次：查询逾期的隐患，修改状态
     */

    @Scheduled(cron = "0 0/1 * * * ?")
    public void updateDangerStateOfOvertime() {

        if("cluster".equals(cluster)){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time=format.format(new Date());
        String jobName = "updateDangerStateOfOvertime" +time;


        //为了便于区分key，增加后缀_redisson
        RLock lock = redisson.getLock(jobName);
        try {
            //拿锁失败10停止尝试，20秒后直接释放锁 无论是返回 true 还是 false，都会继续执行之后的代码。
            lock.tryLock(10, 20, TimeUnit.SECONDS);
            //为了防止重复
            if (!redisUtils.hasKey(jobName + "_updateDangerStateOfOvertime_key")) {
                redisUtils.set(jobName + "_redisson_key", "1");//增加标识
                iLatentDangerService.updateDangerStateOfOvertime();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //释放锁
        }
        }else{
            iLatentDangerService.updateDangerStateOfOvertime();
        }



    }
}