package com.sqx.modules.job.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.modules.discSpinning.entity.DiscSpinningRecord;
import com.sqx.modules.discSpinning.service.DiscSpinningRecordService;
import com.sqx.modules.discSpinning.service.DiscSpinningService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling
public class SpinningTask3 {

    @Resource
    private DiscSpinningService spinningController;
    @Resource
    private DiscSpinningRecordService recordService;

    @Value("${spring.profiles.active}")
    private String profiles;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Scheduled(cron = "0 0/5 * * * ? ")
    public void record() {
        if (!"prod".equals(profiles)) {
            return;
        }
        record("1");
    }

    public void record(String params) {
        logger.info("大转盘到账补偿机制");
        // 获取当前时间
        Date now = DateUtil.date();
        if (StringUtils.isBlank(params)) {
            params = "1";
        }
        // 获取五分钟前的时间
        Date fiveMinutesAgo = DateUtil.offsetMinute(now, Integer.valueOf(params) * -6);
        Date tenMinutesAgo = DateUtil.offsetMinute(now, (Integer.valueOf(params) * -6) - 6);
        // 将五分钟前的时间转换为指定格式的时间字符串，这里采用常见的"yyyy-MM-dd HH:mm:ss"格式
        String fiveMinutesAgoStr = DateUtil.format(fiveMinutesAgo, "yyyy-MM-dd HH:mm:ss");
        String tenMinutesAgoStr = DateUtil.format(tenMinutesAgo, "yyyy-MM-dd HH:mm:ss");

        QueryWrapper<DiscSpinningRecord> recordQueryWrapper = new QueryWrapper<>();
        recordQueryWrapper.isNull("target");
        recordQueryWrapper.isNull("target_id");
        recordQueryWrapper.eq("type", 2);
        //大于
        recordQueryWrapper.lt("create_time", fiveMinutesAgoStr);
        //小于
        recordQueryWrapper.gt("create_time", tenMinutesAgoStr);
        logger.info("大转盘到账补偿时间范围：{}-----{}", tenMinutesAgoStr, fiveMinutesAgoStr);
        List<DiscSpinningRecord> list = recordService.list(recordQueryWrapper);
        ThreadUtil.execAsync(() -> {
            for (DiscSpinningRecord record : list) {
                spinningController.receive1(record);
            }
        });

        logger.info("大转盘到账补偿机制结束");
    }
}
