package com.artfess.bpm.plugin.usercalc.role.runtime;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.artfess.base.feign.UCFeignService;
import com.artfess.base.util.StringUtil;
import com.artfess.bpm.api.constant.BpmConstants;
import com.artfess.bpm.api.constant.ExtractType;
import com.artfess.bpm.api.model.identity.BpmIdentity;
import com.artfess.bpm.api.plugin.core.def.BpmPluginDef;
import com.artfess.bpm.api.plugin.core.session.BpmUserCalcPluginSession;
import com.artfess.bpm.model.identity.DefaultBpmIdentity;
import com.artfess.bpm.plugin.core.runtime.AbstractUserCalcPlugin;
import com.artfess.bpm.plugin.usercalc.role.def.RolePluginDef;
import com.artfess.uc.api.constant.GroupTypeConstant;
import com.artfess.uc.api.impl.model.OrgRel;
import com.artfess.uc.api.impl.model.Role;
import com.artfess.uc.api.model.IGroup;
import com.artfess.uc.api.service.IOrgService;

/**
 * 角色作为流程审批人的插件
 *
 * @company 阿特菲斯信息技术有限公司
 * @author pangq
 * @email pangq@jee-soft.cn
 * @date 2020年6月16日
 */
public class RolePlugin extends AbstractUserCalcPlugin{
    @Resource
    UCFeignService ucFeignService;

    @Override
    public List<BpmIdentity> queryByPluginDef(BpmUserCalcPluginSession pluginSession, BpmPluginDef pluginDef) {
        List<BpmIdentity> identityList=new ArrayList<BpmIdentity>();
        RolePluginDef def = (RolePluginDef)pluginDef;
        String roleCode = def.getRoleCode();
        String roleName = def.getRoleName();
        if(StringUtil.isEmpty(roleCode)) return identityList;

        IOrgService orgEngine= pluginSession.getOrgEngine();
        Map<String, Object> vars= pluginSession.getVariables();
        boolean isReqUc = StringUtil.isEmpty((String)vars.get(BpmConstants.NOT_REQUEST_UC));
        IGroup group = null;
        if (isReqUc || ExtractType.EXACT_EXACT_USER.equals(def.getExtract())) {
            group = orgEngine.getUserGroupService().getGroupByIdOrCode(GroupTypeConstant.ROLE.key(), roleCode);
        }else {
            group = buildRoleGroup(roleCode, roleName);
        }
        BpmIdentity bpmIdentity = getBpmIdentityConverter().convertGroup(group);
        identityList.add(bpmIdentity);
        return identityList;
    }

    private IGroup buildRoleGroup(String roleCode, String roleName) {
        Role role = new Role();
        role.setAlias(roleCode);
        role.setName(roleName);
        return role;
    }
}
