package com.cmvr.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.cmvr.evaluation.model.domain.AeEvaluation;
import com.cmvr.evaluation.service.IAeEvaluationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 评估任务调度
 */
@Slf4j
@Component("evaluation")
@RequiredArgsConstructor
public class AeEvaluationTask {

    private final StringRedisTemplate redisTemplate;

    private final IAeEvaluationService aeEvaluationService;

    public void schedule() {
        String json = redisTemplate.opsForList().leftPop("ae:evaluation:queue");

        if (json == null) {
            return;
        }

        AeEvaluation evaluation = JSON.parseObject(json, AeEvaluation.class);

        try {
            aeEvaluationService.runEvaluation(evaluation);
        } catch (Exception e) {
            log.error("评估执行失败 aeId={}", evaluation.getAeId(), e);
            // 失败重回队列
            redisTemplate.opsForList().rightPush("ae:evaluation:queue", json);
        }
    }
}