package cn.iocoder.yudao.module.system.job.attendance;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.Constants;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.service.attendance.scheduling.AttendanceSchedulingService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
@Slf4j
public class SchedulingJob {
    @Resource
    private AttendanceSchedulingService attendanceSchedulingService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // TODO: 2024/4/22  - 每天晚上24点执行
    @XxlJob("schedulingCycleIncrementJob")
    @TenantJob // --- ⚠️ 这个注解 会将租户列表拉出来 完了后逐个租户执行 定时任务需要注意
    public ReturnT<String> execute() throws Exception {
        // -- 获取每个排班考勤组 有多少数量(也就是周期多少日)
        Map<Long, Integer> map = attendanceSchedulingService.countGroupId();
        if (MapUtil.isEmpty(map)) {
            return ReturnT.SUCCESS;
        }
        for (Map.Entry<Long, Integer> entry : map.entrySet()) {
            String schedulingKey = Constants.SCHEDULING + Constants.UNDERLINE + entry.getKey();
            String value = stringRedisTemplate.opsForValue().get(schedulingKey);
            // -- 如果大于等于周期数 则重置为1
            if (StrUtil.isNotEmpty(value) && Integer.parseInt(value) >= entry.getValue()) {
                stringRedisTemplate.opsForValue().set(schedulingKey, "1");
            } else {
                stringRedisTemplate.opsForValue().increment(schedulingKey);
            }
        }
        // 返回执行成功
        return ReturnT.SUCCESS;
    }
}
