package cn.axzo.workflow.server.controller.listener.error;

import cn.axzo.workflow.core.listener.BpmnAsyncExecutionErrorEventListener;
import cn.axzo.workflow.server.common.annotation.ReporterType;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.flowable.job.api.JobInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 异步任务执行异常的扩展监听器
 *
 * @author wangli
 * @since 2024/4/17 16:59
 */
@Slf4j
@Component
public class ErrorReporterEventListener implements BpmnAsyncExecutionErrorEventListener {
    @Value("${spring.profiles.active}")
    private String profile;
    @Value("${workflow.sendDingTalk:true}")
    private Boolean sendDingTalk;

    @Override
    public void notify(JobInfo jobInfo, Throwable throwable) {
        ReporterType reporterType = ReporterType.ONLY_LOG;
        if (Lists.newArrayList("dev", "test", "pre").contains(profile)) {
            reporterType = ReporterType.BOTH;
        } else if (Lists.newArrayList("live", "master").contains(profile)) {
            reporterType = ReporterType.ONLY_LOG;
        }
        reporterType.executeAction(profile, "异步任务执行异常, 剩余重试次数:" + jobInfo.getRetries(), sendDingTalk, new Object[]{jobInfo}, "act_ru_job", throwable, false);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
