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

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.listener.BpmnTaskEventListener;
import lombok.extern.slf4j.Slf4j;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_TASK_RELATION_ASSIGNEE_INFO_SNAPSHOT;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_TASK_RELATION_ASSIGNEE_LIST_INFO_SNAPSHOT;

/**
 * 任务节点关联的处理人快照保持
 * <p>
 * 注意:Order 值越小,优先级越高
 *
 * @author wangli
 * @since 2023/9/25 18:50
 */
@Slf4j
@Component
public class SnapshotBpmnTaskTaskEventListener implements BpmnTaskEventListener, Ordered {

    @Override
    public void onAssigned(DelegateTask delegateTask) {
        List<BpmnTaskDelegateAssigner> assignerList =
                (List<BpmnTaskDelegateAssigner>) delegateTask.getVariable(INTERNAL_TASK_RELATION_ASSIGNEE_LIST_INFO_SNAPSHOT + delegateTask.getTaskDefinitionKey());
        if (CollectionUtils.isEmpty(assignerList)) {
            return;
        }
        // identityId_identityType
        assignerList.stream().filter(i -> Objects.equals(delegateTask.getAssignee(), i.buildAssigneeId())).findFirst().ifPresent(i -> {
            // 保存每个 taskId 的审批人
            delegateTask.setVariable(INTERNAL_TASK_RELATION_ASSIGNEE_INFO_SNAPSHOT + delegateTask.getId(), i);
        });
    }

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