package com.leanwo.activiti.listener.base;


import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leanwo.activiti.dto.base.TaskCommand;
import com.leanwo.activiti.service.base.impl.UserPreference;
import com.leanwo.activiti.util.SpringUtil;

/**
 * 流程启动后，发起人发起审批节点。
 * 自动完成审批的任务监听器
 * @author YangZhiJie 20210909
 *
 */
public class ProcessStartUserTaskListener implements TaskListener {
	
	private static Logger logger = LoggerFactory.getLogger(ProcessStartUserTaskListener.class);
	
	@Override
	public void notify(DelegateTask delegateTask) {
//		DelegateExecution execution = delegateTask.getExecution();
//		execution.setVariableLocal(UserPreference.COMMENT, "发起人启动审批流程。");
//		execution.setVariable(UserPreference.COMMAND, TaskCommand.APPROVE.toString());

		String taskId = delegateTask.getId();
		String processInstanceId = delegateTask.getProcessInstanceId();
		Long createUserId = (Long) delegateTask.getVariable("CREATE_USER_ID");
		
		delegateTask.setAssignee(createUserId.toString());
		
		Map<String, Object> properties = new HashMap<String, Object>();
		properties.put(UserPreference.COMMENT, "发起人启动审批流程。");
		properties.put(UserPreference.COMMAND, TaskCommand.APPROVE.toString());
		
		
		TaskService taskService = (TaskService) SpringUtil.getSingleBean(TaskService.class);
		taskService.addComment(taskId, processInstanceId, "发起人启动审批流程。");
		// 修复【发起人审批】节点的TaskListener中，调用completeTask造成的BUG。
		// hard fixed by jack 2021-12-14
//		taskService.complete(taskId, properties);
		
		// 异步方法
		//AutoCompleteThread autoCompleteThread = new AutoCompleteThread(delegateTask.getId(), delegateTask.getProcessInstanceId());
		//autoCompleteThread.start();
	}
	
	public class AutoCompleteThread extends Thread{
		
		private String taskId;
		
		private String processInstanceId;
		
		public AutoCompleteThread(String taskId, String processInstanceId) {
			this.taskId = taskId;
			this.processInstanceId = processInstanceId;
		}
		
		@Override
		public void run() {
			this.setName("自动完成用户任务。" + taskId);
			try {
				Thread.sleep(1000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			Map<String, Object> properties = new HashMap<String, Object>();
			properties.put(UserPreference.COMMENT, "发起人启动审批流程。");
			properties.put(UserPreference.COMMAND, TaskCommand.APPROVE.toString());
			
			
			TaskService taskService = (TaskService) SpringUtil.getSingleBean(TaskService.class);
			taskService.addComment(taskId, processInstanceId, "发起人启动审批流程。");
			taskService.complete(taskId, properties);
		}
	}
}
