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

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.common.context.TaskOperationContext;
import cn.axzo.workflow.core.listener.AbstractBpmnEventListener;
import cn.axzo.workflow.core.listener.BpmnTaskEventListener;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

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

import static cn.axzo.workflow.common.constant.BpmnConstants.COMMENT_TYPE_OPERATION_DESC;
import static cn.axzo.workflow.common.constant.BpmnConstants.DUMMY_ASSIGNEE_ID;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_ACTIVITY_RELATION_ASSIGNEE_LIST_INFO_SNAPSHOT;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_TASK_RELATION_ASSIGNEE_INFO;

/**
 * 任务节点关联的处理人快照
 * <p>
 * 注意:Order 值越小,优先级越高
 *
 * @author wangli
 * @since 2023/9/25 18:50
 */
@Slf4j
@Component
@AllArgsConstructor
public class SnapshotBpmnTaskTaskEvent_100_Listener extends AbstractBpmnEventListener<TaskOperationContext> implements BpmnTaskEventListener, Ordered {
    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 100;
    }

    private final RuntimeService runtimeService;
    private final TaskService taskService;

    @Override
    public void onAssigned(DelegateTask delegateTask) {
        log.info("SnapshotBpmnTaskTaskEventListener#onAssigned...{}", delegateTask.getTaskDefinitionKey());
        List<BpmnTaskDelegateAssigner> assignerList = runtimeService.getVariable(delegateTask.getProcessInstanceId(),
                INTERNAL_ACTIVITY_RELATION_ASSIGNEE_LIST_INFO_SNAPSHOT + delegateTask.getTaskDefinitionKey(),
                List.class);
        // identityId_identityType
        ListUtils.emptyIfNull(assignerList).stream()
                .filter(i -> Objects.equals(delegateTask.getAssignee(), i.buildAssigneeId()))
                .findFirst()
                .ifPresent(i -> {
                    // 保存每个 taskId 的审批人
                    delegateTask.setVariable(INTERNAL_TASK_RELATION_ASSIGNEE_INFO + delegateTask.getId(), i.toJson());
                    // 业务指定审批人时, 添加 operationDesc
                    if (Objects.equals(DUMMY_ASSIGNEE_ID, i.buildAssigneeId_1_2_1())) {
                        taskService.addComment(delegateTask.getId(), delegateTask.getProcessInstanceId(),
                                COMMENT_TYPE_OPERATION_DESC, "业务指定审批人");
                    }
                });

        log.info("SnapshotBpmnTaskTaskEventListener#onAssigned...end: {}", delegateTask.getTaskDefinitionKey());
    }
}
