package com.artfess.bpm.plugin.task.taskcopyto.plugin;

import com.artfess.bpm.api.cmd.ActionCmd;
import com.artfess.bpm.api.constant.BpmConstants;
import com.artfess.bpm.api.constant.TemplateConstants;
import com.artfess.bpm.api.constant.TemplateConstants.TEMP_VAR;
import com.artfess.bpm.api.context.ContextThreadUtil;
import com.artfess.bpm.api.model.process.inst.BpmProcessInstance;
import com.artfess.bpm.api.plugin.core.def.BpmTaskPluginDef;
import com.artfess.bpm.api.plugin.core.session.BpmTaskPluginSession;
import com.artfess.bpm.api.service.BpmCopyToService;
import com.artfess.bpm.plugin.core.runtime.AbstractBpmTaskPlugin;
import com.artfess.bpm.plugin.core.util.UserAssignRuleQueryHelper;
import com.artfess.bpm.plugin.task.taskcopyto.def.TaskCopyToPluginDef;
import com.artfess.bpm.plugin.task.taskcopyto.def.model.CopyToItem;
import com.artfess.bpm.plugin.task.tasknotify.helper.NotifyHelper;
import com.artfess.uc.api.model.IUser;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

public class TaskCopyToPlugin extends AbstractBpmTaskPlugin{	
	@Resource
	private BpmCopyToService bpmCopyToService;
	
	@Resource
	private NotifyHelper notifyHelper;
	
	public Void execute(BpmTaskPluginSession pluginSession,
			BpmTaskPluginDef pluginDef) throws Exception {
		
		Map<String,Object> variables = pluginSession.getBpmDelegateTask().getVariables();		
		
		ActionCmd actionCmd = ContextThreadUtil.getActionCmd();
		BpmProcessInstance instance=(BpmProcessInstance) actionCmd.getTransitVars(BpmConstants.PROCESS_INST);
		
		TaskCopyToPluginDef taskCopyToPluginDef = (TaskCopyToPluginDef)pluginDef;
		for(CopyToItem copyToItem:taskCopyToPluginDef.getCopyToItems()){			
			List<IUser> toUsers = UserAssignRuleQueryHelper.queryUsersWithExtract(copyToItem.getUserAssignRules(), pluginSession.getBpmDelegateTask().getVariables());
			bpmCopyToService.copyTo(toUsers, instance,pluginSession.getBpmDelegateTask().getTaskDefinitionKey());
			
			//如果设置了消息类型，表示要发送消息
			//抄送重用“任务完成”的模板，如果需要定义独立的模板类型，请增加常量
			if(copyToItem.getMsgTypes().size()>0){
				
				variables.put(TEMP_VAR.NODE_NAME, pluginSession.getBpmDelegateTask().getName());
				
				notifyHelper.notify(toUsers, copyToItem.getMsgTypes(), TemplateConstants.TYPE_KEY.TASK_COMPLETE,  variables);
			}
		}
		return null;
	}

}
