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.SysUserRoleServiceApi;
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.NodeApproverRole;
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 RoleApproverRule 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<NodeApproverRole> nodeApproverRoleList = mainApprover.getNodeApproverRoleList();
        if (ObjectUtil.isEmpty(nodeApproverRoleList)) {
            return false;
        }

        return true;
    }

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

        List<NodeApproverRole> nodeApproverRoleList = approverConfig.getMainApprover().getNodeApproverRoleList();

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

        for (NodeApproverRole nodeApproverRole : nodeApproverRoleList) {
            List<Long> roleApproverList = getRoleApproverList(nodeApproverRole);
            if (ObjectUtil.isNotEmpty(roleApproverList)) {
                userIdList.addAll(roleApproverList);
            }
        }

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

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

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

    private List<Long> getRoleApproverList(NodeApproverRole nodeApproverRole) {

        if(ObjectUtil.isEmpty(nodeApproverRole.getRoleId())){
            return new ArrayList<>();
        }

        SysUserRoleServiceApi sysUserRoleApi = SpringUtil.getBean(SysUserRoleServiceApi.class);
        List<Long> userIdList = sysUserRoleApi.findUserIdsByRoleId(nodeApproverRole.getRoleId());

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

        return new ArrayList<>();
    }

}




