package com.storlead.centre.dispatch;

import com.storlead.centre.service.AttendanceSignRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalTime;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: storlead-centre-platform
 * @description:
 * @author: chenkq
 * @create: 2026-01-07 14:57
 */

@Slf4j
@Component
public class AttendanceSignDispatchTask {

    @Resource
    private AttendanceSignRecordService attendanceSignRecordService;

    private final ReentrantLock syncLock = new ReentrantLock();

    @Value("${environment}")
    private  String environment;
    /**
     * 同步考勤数据
     * @throws ParseException
     */
    @Scheduled(cron ="0 * * * * ? ")
    public void syncSignData() throws ParseException {

        if (!syncLock.tryLock()) {
            log.warn("syncSignData 正在执行中，本次调度跳过");
            return;
        }
        try {
            if(!"prod".equals(environment)) {
                return;
            }
            LocalTime now = LocalTime.now();

            // ===== 总时间窗：06:00 – 22:30 =====
            if (now.isBefore(LocalTime.of(6, 0))
                    || now.isAfter(LocalTime.of(22, 30))) {
                return;
            }

            boolean morningHighFrequency =
                    (now.getHour() == 8 && now.getMinute() >= 30)
                            || (now.getHour() == 9 && now.getMinute() <= 10);

            boolean eveningHighFrequency =
                    (now.getHour() == 18)
                            || (now.getHour() == 19 && now.getMinute() <= 40);

            boolean highFrequency = morningHighFrequency || eveningHighFrequency;
            // 非高频时间：只允许 5 分钟一次
            if (!highFrequency && now.getMinute() % 5 != 0) {
                return;
            }

            attendanceSignRecordService.getSaveSignRecord();
            attendanceSignRecordService.getDelayedSign();

        } catch (Exception e) {
            log.error("syncSignData error ----",e);
        } finally {
            // 👉 确保一定释放锁（防死锁）
            syncLock.unlock();
        }
    }

}
