package cn.axzo.workflow.core.engine.behavior;

import cn.axzo.workflow.core.service.ExtAxHiTaskInstService;
import org.flowable.bpmn.model.Activity;
import org.flowable.bpmn.model.ReceiveTask;
import org.flowable.bpmn.model.ServiceTask;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior;
import org.flowable.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior;
import org.flowable.engine.impl.bpmn.behavior.ReceiveTaskActivityBehavior;
import org.flowable.engine.impl.bpmn.behavior.SequentialMultiInstanceBehavior;
import org.flowable.engine.impl.bpmn.behavior.ServiceTaskDelegateExpressionActivityBehavior;
import org.flowable.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.flowable.engine.impl.bpmn.parser.factory.DefaultActivityBehaviorFactory;

/**
 * 通过 Flowable 引擎工厂,替换多实例的行为
 * <p>
 * 主要解决多实例如果设置了自动跳过功能, 在历史数据中可以看到被跳过的任务. Flowable 默认的行为不存历史表.
 *
 * @author wangli
 * @since 2023/7/29 00:34
 */
public class CustomActivityBehaviorFactory extends DefaultActivityBehaviorFactory {
    private ExtAxHiTaskInstService hiTaskInstService;
    @Override
    public ParallelMultiInstanceBehavior createParallelMultiInstanceBehavior(Activity activity,
                                                                             AbstractBpmnActivityBehavior innerActivityBehavior) {
        return new CustomParallelMultiInstanceBehavior(activity, innerActivityBehavior);
    }

    @Override
    public SequentialMultiInstanceBehavior createSequentialMultiInstanceBehavior(Activity activity,
                                                                                 AbstractBpmnActivityBehavior innerActivityBehavior) {
        return new CustomSequentialMultiInstanceBehavior(activity, innerActivityBehavior);
    }

    @Override
    public UserTaskActivityBehavior createUserTaskActivityBehavior(UserTask userTask) {
        return new CustomUserTaskActivityBehavior(userTask);
    }

    @Override
    public ReceiveTaskActivityBehavior createReceiveTaskActivityBehavior(ReceiveTask receiveTask) {
        return new CustomReceiveTaskActivityBehavior(receiveTask, hiTaskInstService);
    }

    @Override
    public ServiceTaskDelegateExpressionActivityBehavior createServiceTaskDelegateExpressionActivityBehavior(ServiceTask serviceTask) {

        Expression delegateExpression = expressionManager.createExpression(serviceTask.getImplementation());
        return new CustomServiceTaskDelegateExpressionActivityBehavior(serviceTask.getId(), delegateExpression,
                getSkipExpressionFromServiceTask(serviceTask),
                createFieldDeclarations(serviceTask.getFieldExtensions()),
                serviceTask.getMapExceptions(), serviceTask.isTriggerable(), serviceTask);
    }

    public void setHiTaskInstService(ExtAxHiTaskInstService hiTaskInstService) {
        this.hiTaskInstService = hiTaskInstService;
    }
}
