package cn.axzo.workflow.server.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 重复提交的时间参数动态处理
 *
 * @author wangli
 * @since 2024/1/19 16:49
 */
@Component
@RefreshScope
@Slf4j
public class RepeatSubmitResolver {

    private final Environment environment;

    public RepeatSubmitResolver(Environment environment) {this.environment = environment;}

    public long resolveExpression(String expression, long interval) {
        // 使用 Environment 解析表达式
        String resolved = environment.resolvePlaceholders(expression);
        try {
            if (Objects.equals("${workflow.repeatSubmit.interval}", resolved)) {
                return interval;
            }
            return Integer.parseInt(resolved);
        } catch (NumberFormatException e) {
            // 处理异常或使用默认值
            log.error("@RepeatSubmit 注解的 intervalExpression 属性请使用 Spel 表达式获取环境变量中的超时时间配置, 当前的表达式存在问题, 以使用默认的超时时间, " +
                    "Spel= {}", expression);
            return interval; // 默认值
        }
    }
}
