package org.springblade.flow.engine.custom.behavior.impl;

import static org.springblade.flow.engine.custom.constants.BasicActivitiConstants.exActivitiPrefixURL;
import static org.springblade.flow.engine.custom.constants.BasicActivitiConstants.extensionAttributeName;
import static org.springblade.flow.engine.custom.constants.GlobalProcessVariableConstants.FLOW_ENGINE_ID;

import java.util.HashMap;
import java.util.List;

import org.flowable.bpmn.model.Activity;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior;
import org.flowable.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior;
import org.springblade.flow.base.util.BpmnModelUtils;
import org.springblade.flow.base.util.SpringContextHolder;
import org.springblade.flow.engine.assembly.UserTaskExPropertyDTO;
import org.springblade.flow.engine.custom.helper.UserTaskNodeHelper;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 此类不能注入到Spring容器中  因为行为类实现类不可以是单例的
 */
@Slf4j
public class CustomParallelMultiInstanceBehavior extends
        ParallelMultiInstanceBehavior {

    public CustomParallelMultiInstanceBehavior(Activity activity, AbstractBpmnActivityBehavior originalActivityBehavior) {
        super(activity, originalActivityBehavior);
    }

    @Override
    protected int createInstances(DelegateExecution execution) {
        log.info("创建多实例开始啦: {}  ", execution);
        String activityId = execution.getCurrentActivityId();
        String processDefinitionId = execution.getProcessDefinitionId();
        Process process = BpmnModelUtils.getBpmnModelMainProcess(processDefinitionId);

        UserTaskNodeHelper userTaskNodeHelper = SpringContextHolder.getBean(UserTaskNodeHelper.class);
        UserTask activity = (UserTask) process.getFlowElement(activityId);
        String property = activity.getAttributeValue(exActivitiPrefixURL, extensionAttributeName);
        UserTaskExPropertyDTO exPropertyDTO = JSONObject.parseObject(property, new TypeReference<UserTaskExPropertyDTO>() {});
        String variableName = activityId + "assigneeList";
        String flowId = execution.getVariable(FLOW_ENGINE_ID,String.class);
        HashMap<String, String> taskInfoMap = MapUtil.newHashMap();
        taskInfoMap.put("processDefinitionId",execution.getProcessDefinitionId());
        taskInfoMap.put("taskDefinitionKey",activity.getId());
        taskInfoMap.put("processInstanceId",execution.getProcessInstanceId());
        List<String> assignUserList = userTaskNodeHelper.getAssignUserList(exPropertyDTO, taskInfoMap, flowId);
        setLoopVariable(execution,variableName,assignUserList);
        int instances = super.createInstances(execution);
        return instances;
}



}
