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

import com.artfess.base.groovy.GroovyScriptEngine;
import com.artfess.base.model.HtJsonNodeFactory;
import com.artfess.base.model.HtObjectNode;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.bpm.api.cmd.ActionCmd;
import com.artfess.bpm.api.context.BpmContextUtil;
import com.artfess.bpm.api.context.ContextThreadUtil;
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.engine.task.cmd.DefaultTaskFinishCmd;
import com.artfess.bpm.persistence.manager.BpmProcessInstanceManager;
import com.artfess.bpm.persistence.model.DefaultBpmProcessInstance;
import com.artfess.bpm.plugin.core.runtime.AbstractUserCalcPlugin;
import com.artfess.bpm.plugin.usercalc.hrScript.def.HrScriptPluginDef;
import com.fasterxml.jackson.databind.node.ObjectNode;

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

/**
 * 人员脚本获取插件。
 * <pre> 
 * 构建组：x5-bpmx-plugin
 * 作者：ray
 * 邮箱:zhangyg@jee-soft.cn
 * 日期:2014-6-16-下午3:06:18
 * 版权：广州宏天软件有限公司版权所有
 * </pre>
 */
public class HrScriptPlugin extends AbstractUserCalcPlugin{
	@Resource
	GroovyScriptEngine groovyScriptEngine;
	@Resource
	BoDataService boDataService;
    @Resource
    BpmInstService bpmInstService;
	@Resource
	BpmProcessInstanceManager bpmProcessInstanceManager;
	@SuppressWarnings("unchecked")
	@Override
	public List<BpmIdentity> queryByPluginDef(BpmUserCalcPluginSession pluginSession, BpmPluginDef pluginDef) throws Exception {
		HrScriptPluginDef def=(HrScriptPluginDef)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();
		
		ActionCmd actionCmd = ContextThreadUtil.getActionCmd();
		if((BeanUtils.isEmpty(actionCmd) || boMap.isEmpty()) && variables.containsKey("instanceId_") ){
			String instanceId = (String) variables.get("instanceId_");
			DefaultBpmProcessInstance bpmProcessInstance = bpmProcessInstanceManager.get(instanceId);
			List<ObjectNode> boDatas = boDataService.getDataByInst(bpmProcessInstance);
			boMap=new HashMap<String, ObjectNode>();
			for(ObjectNode data:boDatas){
				String code="";
				if(data.hasNonNull("boDefAlias")){
					code = data.get("boDefAlias").asText();
				}else  {
					code=data.get("boDef").get("alias").asText();
				}
				boMap.put(code, data.has("data")?(ObjectNode)data.get("data"):data);
			}
			DefaultTaskFinishCmd taskCmd = new DefaultTaskFinishCmd();
			taskCmd.setVariables(variables);
			ContextThreadUtil.setActionCmd(taskCmd);
			
		} 
        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)){
			Map<String, HtObjectNode> newMap =new HashMap<>();
			for (Iterator<Entry<String, ObjectNode>> iterator = boMap.entrySet().iterator(); iterator.hasNext();) {
				Entry<String, ObjectNode> next = iterator.next();
				newMap.put(next.getKey(),HtJsonNodeFactory.build().htObjectNode(next.getValue()));
			}
			variables.putAll(newMap); 
		}
		 
		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;
	}

}
