package cn.stylefeng.workflow.instance.core.condition;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.workflow.api.enums.ApproverTypeEnum;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.api.pojo.config.node.approver.ApproverConfig;
import cn.stylefeng.workflow.api.pojo.config.node.approver.ApproverSummary;
import cn.stylefeng.workflow.api.pojo.config.node.approver.detail.NodeApproverPerson;
import cn.stylefeng.workflow.instance.core.condition.base.BaseApproverRule;

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

public class PersonApproverRule extends BaseApproverRule {

    @Override
    public boolean approverEvaluate(InstanceContext instanceContext, ApproverConfig approverConfig) {

        ApproverSummary mainApprover = approverConfig.getMainApprover();
        if (ObjectUtil.isEmpty(mainApprover)) {
            return false;
        }

        if (!ApproverTypeEnum.ORG_SELECT.getValue().equals(mainApprover.getApproverType())) {
            return false;
        }

        List<NodeApproverPerson> nodeApproverPersonList = mainApprover.getNodeApproverPersonList();
        if (ObjectUtil.isEmpty(nodeApproverPersonList)) {
            return false;
        }

        return true;

    }

    @Override
    public void approverExecute(InstanceContext instanceContext, ApproverConfig approverConfig) {

        List<NodeApproverPerson> nodeApproverPersonList = approverConfig.getMainApprover().getNodeApproverPersonList();

        List<Long> userIdList = nodeApproverPersonList.stream().map(NodeApproverPerson::getUserId).collect(Collectors.toList());

        if (ObjectUtil.isEmpty(userIdList)) {
            return;
        }

        setResult(userIdList);
    }

    @Override
    public String getBaseRuleName() {
        return PersonApproverRule.class.getName();
    }

    @Override
    public int getBaseRulePriority() {
        return 100;
    }

}
