package cn.axzo.workflow.core.engine.job.exception.handle;

import cn.axzo.workflow.common.exception.WorkflowEngineException;
import lombok.extern.slf4j.Slf4j;
import org.flowable.job.api.JobInfo;
import org.flowable.job.service.JobServiceConfiguration;
import org.flowable.job.service.impl.asyncexecutor.AsyncRunnableExecutionExceptionHandler;

import java.util.Objects;

/**
 * 解决异步任务执行过程中, 抛出的 WorkflowEngineException 正常的业务异常.
 *
 * @author wangli
 * @since 2024/6/26 15:53
 */
@Slf4j
public class CustomWorkflowEngineExceptionHandler implements AsyncRunnableExecutionExceptionHandler {
    @Override
    public boolean handleException(JobServiceConfiguration jobServiceConfiguration, JobInfo job, Throwable e) {
        Throwable rootCause = getRootCause(e);
//        if (rootCause.getClass().isAssignableFrom(WorkflowEngineException.class)) {
//            WorkflowEngineException workflowEngineException = (WorkflowEngineException) rootCause;
//            if (Objects.equals(workflowEngineException.getCode(), "99806020")) {
//                log.info("AsyncApproveTaskJobHandler execute exception code: {} info: {}",
//                        workflowEngineException.getCode(), rootCause.getMessage(), rootCause);
//                return true;
//            }
//        }
        log.warn("Async Runnable Execution Exception: {}", rootCause.getMessage(), e);
        boolean assignableFrom = WorkflowEngineException.class.isAssignableFrom(rootCause.getClass());
        log.info("CustomWorkflowEngineExceptionHandler result : {}" , assignableFrom);
        return assignableFrom;
    }

    private Throwable getRootCause(Throwable throwable) {
        while (Objects.nonNull(throwable.getCause())) {
            throwable = throwable.getCause();
        }
        return throwable;
    }
}
