package cn.axzo.workflow.core.deletage.approverscope;

import cn.axzo.workflow.common.model.dto.CooperationOrgDTO;
import cn.axzo.workflow.common.model.dto.CooperationOrgDTO.OrgScope;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.common.utils.BpmnMetaParserHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

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

import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_ACTIVITY_RELATION_ASSIGNEE_LIST_INFO_SNAPSHOT;

/**
 * "审批范围"选择"上级节点所在范围"
 * @author syl
 * @date 2023/11/21
 */
@Slf4j
@Component
public class PreTaskUserProcessor implements ApproverScopeProcessor {

    @Override
    public ApproverScopeDTO build(FlowElement flowElement, DelegateExecution execution) {
        Optional<UserTask> preUserTaskOpt = BpmnMetaParserHelper.getPreNode(flowElement, execution, null);
        if (!preUserTaskOpt.isPresent()) {
            log.info("the current node has no pre node, skip");
            return ApproverScopeDTO.builder().build();
        }

        // 上级节点
        String preActivityId = preUserTaskOpt.get().getId();
        // 获取上一级节点
        List<BpmnTaskDelegateAssigner> assigners = (List<BpmnTaskDelegateAssigner>) execution
                .getVariableLocal(INTERNAL_ACTIVITY_RELATION_ASSIGNEE_LIST_INFO_SNAPSHOT + preActivityId);
        List<OrgScope> entOrg = CollectionUtils.emptyIfNull(assigners).stream()
                .map(a -> {
                    CooperationOrgDTO.OrgScope orgScope = new CooperationOrgDTO.OrgScope()
                            .setWorkspaceId(Long.valueOf(a.getTenantId()));
                    if (StringUtils.isNotBlank(a.getOuId())) {
                        orgScope.setOuId(Long.valueOf(a.getOuId()));
                    }
                    return orgScope;
                })
                .collect(Collectors.toList());
        return ApproverScopeDTO.builder().orgScopes(entOrg)
                .workerTeamScopes(entOrg).build();
    }

}
