package com.codvision.workflow.listener;


import com.codvision.cachecore.utils.RedisUtil;
import com.codvision.workflow.service.WorkFlowRecordService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.FlowableMultiInstanceActivityCompletedEvent;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.codvision.workflow.constant.CacheContant.WORK_FLOW_MULTI_INSTANCE_COMPLETED;


/**
 * 多实例全局监听器
 * @author hxl
 */
@Component
@RequiredArgsConstructor
public class GlobalWorkFlowMultiInstanceListener extends AbstractFlowableEngineEventListener {

    private final TaskService taskService;
    private final WorkFlowRecordService workFlowRecordService;
    public static final String PARALLEL_MULTI_INSTANCE_BEHAVIOR = "org.flowable.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior";

    @Override
    protected void multiInstanceActivityCompletedWithCondition(FlowableMultiInstanceActivityCompletedEvent event) {
        // 非并行会签则直接返回
        if (!PARALLEL_MULTI_INSTANCE_BEHAVIOR.equals(event.getBehaviorClass())) {
            return;
        }

        // 获取已完成的用户节点ID
        String key = WORK_FLOW_MULTI_INSTANCE_COMPLETED + event.getActivityId();
        Set<String> cacheSet = RedisUtil.get(key);
        if (CollectionUtils.isEmpty(cacheSet)) {
            return;
        }

        // 获取当前正在执行的用户节点信息
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(event.getProcessInstanceId()).taskDefinitionKey(event.getActivityId()).list();
        if (CollectionUtils.isEmpty(tasks)) {
            return;
        }

        // 获取未完成的用户节点ID
        List<String> taskIds = tasks.stream().map(Task::getId).filter(id -> !cacheSet.contains(id)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(taskIds)) {
            RedisUtil.del(key);
            return;
        }

        // 清除未完成的用户节点的操作记录
        workFlowRecordService.delByInstanceIdAndActivityIdAndTaskIds(event.getProcessInstanceId(), event.getActivityId(), taskIds);
        RedisUtil.del(key);
    }
}
