package com.td.WaDa.game.comsnbapply.scheduled;

import com.td.WaDa.game.comsnbapply.pojo.ComSnbApply;
import com.td.WaDa.game.comsnbapply.service.ComSnbApplyService;
import com.td.WaDa.game.comsnbapply.vo.ComSnbApplyVo;
import com.td.WaDa.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 后台定时任务
 *
 * @author:slambb
 * @date:2022/3/15
 */
@Service
@Slf4j
@Conditional(IPCondition.class)
public class BackService {

    @Autowired
    private ComSnbApplyService comSnbApplyService;

    @Autowired
    private RedisSettingMap redisSettingMap;

    @Autowired
    private RedisLock redisLock;

    @PostConstruct
    public void init() {
        log.info("apply snb run task...");
    }

    @Scheduled(cron = "0/10 * * * * *")
    public void scheduleTask() {
        //log.info("task running....");
        //todo 处理是否自动审查
        if ("N".equals(redisSettingMap.getSysSettingTaskMap().getApplyAutoExamine())) {
            return;
        }
        long time = System.currentTimeMillis() + RedisData.getAutoApplyTimeout();
        String _redisKey = "LOCK:COM_SNB_APPLY:AUTO";
        if (!redisLock.lock(_redisKey, String.valueOf(time))) {
            log.info("正在自动审查中..！");
            return;
        }
        //进入自动审核,看看后面是否需要限制数量
        ComSnbApplyVo getComSnbApplyVo = new ComSnbApplyVo();
        getComSnbApplyVo.setIsState(0);//查找正在申请中的数据，isState = 0;
        List<ComSnbApplyVo> comSnbApplyVos = comSnbApplyService.list(getComSnbApplyVo).getData();
        //log.info("审查任务数量:{}个", comSnbApplyVos.size());
        for (ComSnbApplyVo comSnbApplyVo : comSnbApplyVos) {
            //1.snb 在[max,min]区间，才能过审 2.如果申请次数不超过限制次数，则过审
            if (comSnbApplyVo.getSnb() <= redisSettingMap.getSysSettingTaskMap().getConditionSnbMax()
                    && comSnbApplyVo.getSnb() >= redisSettingMap.getSysSettingTaskMap().getConditionSnbMin()
                    && comSnbApplyVo.getCount() <= redisSettingMap.getSysSettingTaskMap().getApplyCount()
            ) {
                //全部给通过
                comSnbApplyVo.setIsState(1);
            }
        }
        comSnbApplyService.saveAll(CopyUtil.copyList(comSnbApplyVos, ComSnbApply.class));
        redisLock.unlock(_redisKey, String.valueOf(time));
        //log.info("正在自动审查中任务结束");
    }
}