package cn.axzo.workflow.core.deletage;

import cn.axzo.karma.client.feign.FlowSupportApi;
import cn.axzo.karma.client.model.request.ListFlowTaskAssignerReq;
import cn.axzo.karma.client.model.response.FlowTaskAssignerResp;
import cn.axzo.workflow.common.enums.ApproverSpecifyEnum;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.deletage.approverscope.ApproverScopeDTO;
import cn.hutool.core.bean.BeanUtil;
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.stream.Collectors;

/**
 * 基于"身份"查询审批人
 *
 * @author wangli
 * @since 2023/11/16 11:38
 */
@Slf4j
@Component
public class IdentityTaskAssigneeSelector extends AbstractBpmnTaskAssigneeSelector {

    @Autowired
    private FlowSupportApi flowSupportApi;

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

    @Override
    protected List<BpmnTaskDelegateAssigner> invokeService(UserTask userTask, DelegateExecution execution,
                                                           ApproverScopeDTO scopeDto) {
        ListFlowTaskAssignerReq req = ListFlowTaskAssignerReq.builder()
                .orgScopes(scopeDto.getOrgScopes().stream()
                        .map(e -> BeanUtil
                                .copyProperties(e, ListFlowTaskAssignerReq.OrgScope.class))
                        .collect(Collectors.toList()))
                .workerTeamScopes(scopeDto.getWorkerTeamScopes().stream()
                        .map(w -> BeanUtil
                                .copyProperties(w, ListFlowTaskAssignerReq.OrgScope.class))
                        .collect(Collectors.toList()))
                .identityCodes(super.getTypes(userTask))
                .build();

        List<FlowTaskAssignerResp> flowTaskAssigners =
                parseApiResult(() -> flowSupportApi.listTaskAssignerByIdentity(req), "通过身份查询审批人", req);

        if (CollUtil.isEmpty(flowTaskAssigners)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(flowTaskAssigners, BpmnTaskDelegateAssigner.class);
    }
}
