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

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.sys.api.SysUserOrgServiceApi;
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.NodeApproverPosition;
import cn.stylefeng.workflow.instance.core.condition.base.BaseApproverRule;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class PositionApproverRule 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<NodeApproverPosition> nodeApproverPositionList = mainApprover.getNodeApproverPositionList();
        if (ObjectUtil.isEmpty(nodeApproverPositionList)) {
            return false;
        }

        return true;
    }

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

        List<NodeApproverPosition> nodeApproverPositionList = approverConfig.getMainApprover().getNodeApproverPositionList();

        Set<Long> userIdList = new LinkedHashSet<>();

        for (NodeApproverPosition nodeApproverPosition : nodeApproverPositionList) {
            List<Long> tempUserIdList = getPositionApproverList(nodeApproverPosition);
            if (ObjectUtil.isNotEmpty(tempUserIdList)) {
                userIdList.addAll(tempUserIdList);
            }
        }

        setResult(new ArrayList<>(userIdList));
    }

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

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

    private List<Long> getPositionApproverList(NodeApproverPosition nodeApproverPosition) {
        Long positionId = nodeApproverPosition.getPositionId();

        SysUserOrgServiceApi userOrgServiceApi = SpringUtil.getBean(SysUserOrgServiceApi.class);

        if (ObjectUtil.isEmpty(nodeApproverPosition.getOrgId()) || ObjectUtil.isEmpty(positionId)) {
            return new ArrayList<>();
        }
        List<Long> positionUserIdList = userOrgServiceApi.getPositionUserList(nodeApproverPosition.getOrgId(), positionId);

        if (ObjectUtil.isNotEmpty(positionUserIdList)) {
            return positionUserIdList;
        }

        return new ArrayList<>();
    }

}
