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

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.common.Constants;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.dal.dataobject.attendance.punchrecord.AttendancePunchRecordDO;
import cn.iocoder.yudao.module.system.dal.mysql.attendance.punchrecord.AttendancePunchRecordMapper;
import cn.iocoder.yudao.module.system.service.attendance.punch.dto.AttendanceOnTheDayDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;

@Component
@Slf4j
public class AttendanceMissingCardJob {

    // TODO: 2024/4/22  - 每十分钟执行一次 将漏打卡的设为缺卡 这里的update要保证命中索引 保证是行锁 不然容易导致锁表

    @Resource
    private AttendancePunchRecordMapper attendancePunchRecordMapper;

    @XxlJob("attendanceMissingCardJob")
    @TenantJob // --- ⚠️ 这个注解 会将租户列表拉出来 完了后逐个租户执行 定时任务需要注意
    public ReturnT<String> execute() throws Exception {
        log.info("开始 修改考勤缺卡");
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(Constants.REPO_DATE_FORMAT);
        String yesterdayStr = LocalDateTimeUtil.offset(now, -1, ChronoUnit.DAYS).format(Constants.REPO_DATE_FORMAT);
        LambdaQueryWrapper<AttendancePunchRecordDO> le = new LambdaQueryWrapper<AttendancePunchRecordDO>()
                .in(AttendancePunchRecordDO::getDayTime, Arrays.asList(time, yesterdayStr))
                .eq(AttendancePunchRecordDO::getNextDayFlag, Constants.TRUE)
                .eq(AttendancePunchRecordDO::getStatus, AttendanceOnTheDayDTO.PUNCH_STATUS_UN_PUNCH)
                .le(AttendancePunchRecordDO::getLatestPunchTime, now);
        AttendancePunchRecordDO attendancePunchRecordDO = new AttendancePunchRecordDO();
        attendancePunchRecordDO.setStatus(AttendanceOnTheDayDTO.PUNCH_STATUS_MISS).setNextDayFlag(Constants.FALSE);
        attendancePunchRecordMapper.update(attendancePunchRecordDO, le);
        log.info("结束 修改考勤缺卡");
        // 返回执行成功
        return ReturnT.SUCCESS;
    }

}
