package cn.axzo.workflow.core.deletage;

import cn.axzo.tyr.client.feign.TyrSaasRoleUserApi;
import cn.axzo.tyr.client.model.roleuser.dto.SaasRoleUserDTO;
import cn.axzo.tyr.client.model.roleuser.req.RoleUserParam;
import cn.axzo.workflow.common.enums.ApproverSpecifyEnum;
import cn.axzo.workflow.common.model.dto.CooperationOrgDTO.OrgScope;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.deletage.approverscope.ApproverScopeDTO;
import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 基于"角色"查询审批人
 *
 * @author wangli
 * @since 2023/11/16 11:37
 */
@Slf4j
@Component
public class RoleTaskAssigneeSelector extends AbstractBpmnTaskAssigneeSelector {

    @Autowired
    private TyrSaasRoleUserApi tyrSaasRoleUserApi;

    @Override
    public boolean support(String param) {
        return ApproverSpecifyEnum.role.getType().equals(param);
    }

    @Override
    protected List<BpmnTaskDelegateAssigner> invokeService(UserTask userTask, DelegateExecution execution,
                                                           ApproverScopeDTO scopeDto) {
        Set<Long> workspaceIdSet = scopeDto.getOrgScopes().stream()
                .map(OrgScope::getWorkspaceId)
                .collect(Collectors.toSet());


        // ouIds、workspaceIds 只能传其中一个  然后代码过滤
        RoleUserParam param = RoleUserParam.builder()
                .roleIds(super.getTypes(userTask).stream().map(Long::valueOf).collect(Collectors.toSet()))
                .ouIds(scopeDto.getOrgScopes().stream()
                        .map(OrgScope::getOuId)
                        .collect(Collectors.toList()))
                .build();
        param.setPageSize(-1L);
        List<SaasRoleUserDTO> flowTaskAssigners = parseApiResult(() -> tyrSaasRoleUserApi.roleUserList(param),
                "通过角色查询审批人", param)
                .stream().filter(f -> workspaceIdSet.contains(f.getWorkspaceId()))
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(flowTaskAssigners)) {
            return Collections.emptyList();
        }
        return flowTaskAssigners.stream().map(u -> BpmnTaskDelegateAssigner.builder()
                        .assignee(String.valueOf(u.getIdentityId()))
                        .assigneeType(String.valueOf(u.getIdentityType()))
                        .tenantId(String.valueOf(u.getWorkspaceId()))
                        .ouId(String.valueOf(u.getOuId()))
                        .personId(String.valueOf(u.getNaturalPersonId()))
                        .build())
                .collect(Collectors.toList());
    }

}
