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

import cn.axzo.workflow.common.enums.WorkspaceType;
import cn.axzo.workflow.common.model.dto.CooperationOrgDTO;
import cn.axzo.workflow.common.model.dto.CooperationOrgDTO.OrgScope;
import cn.hutool.core.collection.CollUtil;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

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

/**
 * "审批范围"选择"所在单位"
 *
 * @author syl
 * @date 2023/11/21
 */
@Component
public class EntWorkspaceProcessor implements ApproverScopeProcessor {

    @Override
    public ApproverScopeDTO build(FlowElement flowElement, DelegateExecution execution) {
        // 获取组织信息
        CooperationOrgDTO orgDTO = (CooperationOrgDTO) execution.getVariables().get(BIZ_ORG_RELATION);
        ApproverScopeDTO build = ApproverScopeDTO.builder().build();
        if (Objects.isNull(orgDTO)) {
            return build;
        }

        if (!CollectionUtils.isEmpty(orgDTO.getOrgScopes())) {
            List<OrgScope> orgScopes = orgDTO.getOrgScopes().stream()
                    .filter(o -> Objects.equals(WorkspaceType.ENT, WorkspaceType.getType(o.getWorkspaceType()))
                            || Objects.equals(WorkspaceType.OMS, WorkspaceType.getType(o.getWorkspaceType())))
                    .collect(Collectors.toList());
            build.setOrgScopes(orgScopes);
        }

        if (!CollectionUtils.isEmpty(orgDTO.getWorkerTeamScopes())) {
            List<OrgScope> workerTeamScopes = CollUtil.defaultIfEmpty(orgDTO.getWorkerTeamScopes(),
                            Collections.emptyList())
                    .stream()
                    .filter(o -> WorkspaceType.ENT == WorkspaceType.getType(o.getWorkspaceType()))
                    .collect(Collectors.toList());
            build.setWorkerTeamScopes(workerTeamScopes);
        }
        return build;
    }

}
