package com.chinaweal.aiccs.schedule;

import com.chinaweal.aiccs.door.service.IJgmhPortalTodoService;
import com.chinaweal.aiccs.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 统一监管门户待办推送定时任务
 * 每30分钟扫描推送记录表，将待推送的记录推送到统一监管门户
 */
@Slf4j
@Configuration
@EnableScheduling
public class JgmhPortalTodoPushScheduled {

    private static final String REDIS_LOCK_KEY = "schedule:jgmhPortalTodoPush:lock";
    private static final int REDIS_LOCK_TIMEOUT = 30 * 60; // 30分钟

    @Autowired
    private IJgmhPortalTodoService jgmhPortalTodoService;

    @Autowired
    private RedisService redisService;

    @Scheduled(cron = "${scheduling.cron.jgmhPortalTodoPush:-}")
    public void pushTodoItems() {
        if (!acquireLock()) {
            log.warn("【统一监管门户待办推送任务】上一次执行尚未完成或锁已存在，本次跳过");
            return;
        }

        try {
            log.info("【统一监管门户待办推送任务】开始执行");
            jgmhPortalTodoService.pushPendingTodoItems();
            log.info("【统一监管门户待办推送任务】执行完成");
        } catch (Exception e) {
            log.error("【统一监管门户待办推送任务】执行异常：{}", e.getMessage(), e);
        } finally {
            releaseLock();
        }
    }

    private boolean acquireLock() {
        if (redisService.exists(REDIS_LOCK_KEY)) {
            return false;
        }
        redisService.set(REDIS_LOCK_KEY, "1", REDIS_LOCK_TIMEOUT);
        return true;
    }

    private void releaseLock() {
        redisService.remove(REDIS_LOCK_KEY);
    }
}
