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

import cn.hutool.core.date.DateUtil;
import com.td.boss.game.complayerland.service.ComPlayerDisasterLogService;
import com.td.boss.game.complayers.service.ComPlayersService;
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 ComPlayerDisasterWeekTask extends QuartzJobBean {

    @Autowired
    private ComPlayerDisasterLogService disasterLogService;
    @Autowired
    private ComPlayersService comPlayersService;
    @Autowired
    private RedisLock redisLock;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        log.info("每周拉取灾难数据周期任务开始");

        long time = System.currentTimeMillis() + RedisData.getDisastersWeekTimeout();
        String _redisKey = "LOCK:COM_PLAYER_DISASTER:WEEK:" + DateUtil.format(new Date(), "yyyyMMdd");

        if (!redisLock.lock(_redisKey, String.valueOf(time))) {
            log.info("每周拉取灾难数据周期任务加锁失败！");
            return;
        }

        List<String> userIds = comPlayersService.findUserIds();
        log.info("拉取灾难接口数据周期任务数量:{}个", userIds.size());
        for (String userId : userIds) {
            try {
                disasterLogService.asyncDisaster(userId);
            } catch (Exception e) {
                log.error("触发灾难周期任务异常（周）：" + e.getMessage());
            }
        }

        redisLock.unlock(_redisKey, String.valueOf(time));
        log.info("每周拉取灾难数据周期任务结束");
    }
}
