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

import com.artfess.base.groovy.GroovyScriptEngine;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.bpm.api.context.BpmContextUtil;
import com.artfess.bpm.api.model.identity.BpmIdentity;
import com.artfess.bpm.api.model.process.inst.BpmProcessInstance;
import com.artfess.bpm.api.plugin.core.def.BpmPluginDef;
import com.artfess.bpm.api.plugin.core.session.BpmUserCalcPluginSession;
import com.artfess.bpm.api.service.BoDataService;
import com.artfess.bpm.api.service.BpmInstService;
import com.artfess.bpm.plugin.core.runtime.AbstractUserCalcPlugin;
import com.artfess.bpm.plugin.usercalc.script.def.ScriptPluginDef;
import com.fasterxml.jackson.databind.node.ObjectNode;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 人员脚本获取插件。
 * <pre> 
 * 构建组：x5-bpmx-plugin
 * 作者：ray
 * 邮箱:zhangyg@jee-soft.cn
 * 日期:2014-6-16-下午3:06:18
 * 版权：广州宏天软件有限公司版权所有
 * </pre>
 */
public class ScriptPlugin extends AbstractUserCalcPlugin{
	
	@Resource
	GroovyScriptEngine groovyScriptEngine;
    @Resource
    BoDataService boDataService;
    @Resource
    BpmInstService bpmInstService;

	@SuppressWarnings("unchecked")
	@Override
	public List<BpmIdentity> queryByPluginDef(BpmUserCalcPluginSession pluginSession, BpmPluginDef pluginDef) throws Exception{
		ScriptPluginDef def=(ScriptPluginDef)pluginDef;
	 
		String script=def.getScript();
		if(StringUtil.isEmpty(script)){
			return Collections.EMPTY_LIST;
		}
		
		//获取流程变量
		Map<String, Object> variables= pluginSession.getVariables();
		
		
		Map<String,ObjectNode > boMap= BpmContextUtil.getBoFromContext();
        if (BeanUtils.isEmpty(boMap)) {
            BpmProcessInstance bpmProcessInstance = bpmInstService.getProcessInstance(variables.get("instanceId_").toString());
            //1.获取BO数据
            List<ObjectNode> boDatas = boDataService.getDataByInst(bpmProcessInstance);
            //2.设置bo数据到上下文。
            BpmContextUtil.setBoToContext(boDatas);
            boMap = BpmContextUtil.getBoFromContext();
        }
		if(BeanUtils.isNotEmpty(boMap)){
			variables.putAll(boMap); 
		}
		 
		Set<BpmIdentity> set=(Set<BpmIdentity>) groovyScriptEngine.executeObject(script,variables);
		List<BpmIdentity> list=new ArrayList<BpmIdentity>();
		
		list.addAll(set);
		return list;
	}

	@Override
	public boolean supportPreView() {
		return false;
	}

}
