package com.td.boss.game.complayerland.scheduled;

import cn.hutool.core.date.DateUtil;
import com.td.boss.game.complayerland.pojo.ComPlayerDisasterLog;
import com.td.boss.game.complayerland.service.ComPlayerDisasterLogService;
import com.td.boss.util.RedisData;
import com.td.boss.util.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.QuartzJobBean;

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

@Slf4j
@EnableScheduling
public class ComPlayerDisasterDayTask extends QuartzJobBean {

    @Autowired
    private ComPlayerDisasterLogService comPlayerDisasterLogService;
    @Autowired
    private RedisLock redisLock;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        log.info("触发灾难周期任务开始");
        long time = System.currentTimeMillis() + RedisData.getDisastersDayTimeout();
        String _redisKey = "LOCK:COM_PLAYER_DISASTER:DAY:" + DateUtil.format(new Date(), "yyyyMMdd");

        if (!redisLock.lock(_redisKey, String.valueOf(time))) {
            log.info("触发每天灾难任务加锁失败！");
            return;
        }
        //把今天灾难的明细取出来。按照用户编号计算是否有防护。
        List<ComPlayerDisasterLog> disasterLogList = comPlayerDisasterLogService.getTodayDisasterUnEnabledList();
        log.info("触发每天灾难任务：{}个", disasterLogList.size());
        for (ComPlayerDisasterLog disasterLog : disasterLogList) {
            try {
                comPlayerDisasterLogService.ComPlayerDisasterDayTask(disasterLog);
            } catch (Exception e) {
                log.error("触发灾难周期任务异常（天）：" + e.getMessage());
            }
        }
        redisLock.unlock(_redisKey, String.valueOf(time));
        log.info("触发灾难周期任务结束");
    }
}
