package com.unis.flowable.server.service;

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

import com.alibaba.fastjson.JSON;
import com.unis.common.utils.CurrentUtil;
import com.unis.common.utils.DateUtil;

import com.unis.flowable.common.vo.*;
import com.unis.flowable.server.config.PageResponse;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.bpmn.model.SequenceFlow;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Comment;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;


@Service
@Slf4j
public class FlowTaskService{
	
	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private IdentityService identityService;


	@Autowired
	private HistoryService historyService;
	
	@Autowired
	private TaskService taskService;



	@Autowired
	private RepositoryService repositoryService;

	public String startNewTask(StartNewTaskVO startNewTaskVO) {
		try {
			//设置流程启动人
			identityService.setAuthenticatedUserId(startNewTaskVO.getUserId());
			Map<String, Object> variables = new HashMap<String,Object>();
			variables.put("userId", startNewTaskVO.getUserId());
			if(StringUtils.isNotEmpty(startNewTaskVO.getStatusName())) {
				variables.put("statusName", startNewTaskVO.getStatusName());//设置审批状态
			}
			
			variables.put(startNewTaskVO.getStatusKey(), startNewTaskVO.getStatus());
			String businessKey = startNewTaskVO.getBusinessType()+":"+startNewTaskVO.getId();
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(startNewTaskVO.getProcessKey(),businessKey,variables);
			return processInstance.getProcessInstanceId();
		} catch (Exception e) {
			log.error(e.getMessage());
			return null;
		}
		
	}

	/**
	 * 审批
	 * @param completeVO
	 * @return
	 */
	@SuppressWarnings("serial")
	public int complete(
			FlowAbleCompleteVO completeVO
	) {
		Map<String, Object> vars = Maps.newHashMap();
		//获取流程当前节点
		Task singleResult = taskService.createTaskQuery().processInstanceId(completeVO.getProcessId()).singleResult();
		if(singleResult==null) {
			return 0;
		}
		if(!singleResult.getAssignee().contains(completeVO.getUserId())) {
			return -1;
		}
		//获取流程的任务id
		String taskId = singleResult.getId();
		if(StringUtils.isNotEmpty(completeVO.getMessage())){
			Authentication.setAuthenticatedUserId(completeVO.getUserName()+"--"+completeVO.getEvent());
			taskService.addComment(taskId, completeVO.getProcessId(), completeVO.getMessage());//添加审批建议
		}
		//添加审批人
		taskService.setAssignee(taskId, completeVO.getUserId());
		//设置参数
		vars.put("userId", completeVO.getAssignee());
		vars.put(completeVO.getStatusKey(), completeVO.getStatus());
		if(StringUtils.isNotEmpty(completeVO.getComeout())){
			vars.put(completeVO.getComeoutKey(), completeVO.getComeout());
		}
		//提交审批
		taskService.complete(taskId, vars);

		/**
		 * 在完成任务之后，判断流程是否结束
		 如果流程结束了，更新请假单表的状态从1变成2（审核中-->审核完成）
		 */
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()
				.processInstanceId(completeVO.getProcessId())//使用流程实例ID查询
				.singleResult();
		if(pi==null){
			return 2;
		}
		return 1;
	}




	/**
	 * 分配组任务
	 * @return
	 */
	public int completeGroup(
			CompleteGroupVO completeGroupVO
	) {
		Map<String, Object> vars = Maps.newHashMap();
		//获取流程当前节点
		Task singleResult = taskService.createTaskQuery().processInstanceId(completeGroupVO.getProcessId()).singleResult();
		if(singleResult==null) {
			return 0;
		}
		//获取流程的任务id
		String taskId = singleResult.getId();
		//设置参数
		vars.put(completeGroupVO.getStatusKey(), completeGroupVO.getStatus());
		if(StringUtils.isNotEmpty(completeGroupVO.getComeout())){
			vars.put(completeGroupVO.getComeoutKey(), completeGroupVO.getComeout());
		}

		//当前节点添加审批意见
		if(StringUtils.isNotEmpty(completeGroupVO.getMessage())){
			Authentication.setAuthenticatedUserId(completeGroupVO.getUserName()+"--"+completeGroupVO.getEvent());
			taskService.addComment(taskId, completeGroupVO.getProcessId(), completeGroupVO.getMessage());//添加审批建议
		}

		//提交审批
		taskService.complete(taskId, vars);


		/**
		 * 在完成任务之后，判断流程是否结束
		 如果流程结束了，更新请假单表的状态从1变成2（审核中-->审核完成）
		 */
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()
				.processInstanceId(completeGroupVO.getProcessId())//使用流程实例ID查询
				.singleResult();
		if(pi==null){
			return 2;
		}
		return 1;
	}




	/**
	 * 拾取任务，将组任务分给个人任务
	 * @param taskId  任务ID
	 * @param userId  用户ID REQUIRED
	 * @return
	 */
	public int claim(String taskId, String userId) {
		try{
			taskService.claim(taskId,userId);
		}catch (Exception e){
			e.printStackTrace();
		}
		return 1;
	}


	public List<DeploymentList> getTaskUserList(String key, String userId, Integer pageNum, Integer pageSize) {
		new PageResponse().enablePage(pageNum, pageSize);
		//模糊查询该审批人所需要审批的任务
		TaskQuery query = taskService.createTaskQuery().taskAssigneeLike("%"+userId+"%").active()
				.includeProcessVariables().orderByTaskCreateTime().desc();
		
		if(key!=null||!"".equals(key)) {
			query.processDefinitionKey(key);
		}
		
		List<Task> tasks = query.list();
		
		List<DeploymentList> deploymentLists = new ArrayList<DeploymentList>();
		for(Task task:tasks) {
			DeploymentList deploymentList = new DeploymentList();
			deploymentList.setTaskId(task.getId());
			deploymentList.setTaskName(task.getName());
			deploymentList.setCreateTime(task.getCreateTime());
			deploymentList.setProcInsId(query.taskId(task.getId()).singleResult().getProcessInstanceId());
			deploymentList.setProcDefId(query.taskId(task.getId()).singleResult().getProcessDefinitionId());
			//#流程定义表
			ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(deploymentList.getProcDefId()).singleResult();
			deploymentList.setProcdefName(processDefinition.getName());
			deploymentList.setProcdefKey(processDefinition.getKey());
			deploymentList.setKey(task.getTaskDefinitionKey());
			deploymentLists.add(deploymentList);

		}
		return deploymentLists;
	}


	/**
	 * 获取待办列表---不分页
	 * @param userId  用户ID
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List<DeploymentVO> getUserTaskNoPage(String userId) {
		//模糊查询该审批人所需要审批的任务
		TaskQuery query = taskService.createTaskQuery().taskAssigneeLike("%" + userId + "%").active()
				.includeProcessVariables().orderByTaskCreateTime().desc();
		List<Task> tasks = query.list();
		List<DeploymentVO> deploymentLists = new ArrayList<DeploymentVO>();
		for(Task task:tasks) {
			DeploymentVO deploymentList = new DeploymentVO();
			deploymentList.setTaskId(task.getId());
			deploymentList.setTaskName(task.getName());
			deploymentList.setProcInsId(query.taskId(task.getId()).singleResult().getProcessInstanceId());
			deploymentList.setProcDefId(query.taskId(task.getId()).singleResult().getProcessDefinitionId());
			//#流程定义表
			ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(deploymentList.getProcDefId()).singleResult();

			deploymentList.setProcdefName(processDefinition.getName());
			deploymentList.setProcdefKey(processDefinition.getKey());
			String processInstanceId = task.getProcessInstanceId();
			ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
					.processInstanceId(processInstanceId)//使用流程实例ID查询
					.singleResult();//单个对象
			String buniness_key = pi.getBusinessKey();

			if(StringUtils.isNotBlank(buniness_key)){
				//截取字符串，取buniness_key小数点的第2个值
				String businessType = buniness_key.split(":")[0];
				String businessId = buniness_key.split(":")[1];
				deploymentList.setBusinessType(businessType);
				deploymentList.setBusinessId(businessId);
			}

			//查贸易流程变量
			Map object  = (Map) runtimeService.getVariable(task.getExecutionId(),"irptKey");
			if(object!=null){
				deploymentList.setBbq(object.get("bbq").toString());
				deploymentList.setUserCreditCode(object.get("userCreditCode").toString());
				deploymentList.setStartTime(object.get("startTime").toString());
				deploymentList.setStarter(object.get("orgName").toString());
				deploymentList.setUserName(object.get("userName").toString());
				deploymentList.setOrgName(object.get("orgName").toString());
				deploymentList.setAreaCode(object.get("areaCode").toString());
			}
			//转换时间
			String assignTime=DateUtil.getDateFormat(task.getCreateTime(), DateUtil.df);
			deploymentList.setAssignTime(assignTime);
			deploymentList.setUserTaskType("10");
			deploymentLists.add(deploymentList);

		}
		return deploymentLists;
	}


	/**
	 * 获取待办任务组列表---不分页
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List<DeploymentVO> getUserTaskGroupNoPage(String userId,String areaCode) {
		TaskQuery query = taskService.createTaskQuery().taskCandidateUser(userId).active()
				.includeProcessVariables().orderByTaskCreateTime().desc();
		List<Task> tasks = query.list();
		List<DeploymentVO> deploymentLists = new ArrayList<DeploymentVO>();
		for(Task task:tasks) {
			DeploymentVO deploymentList = new DeploymentVO();
			deploymentList.setTaskId(task.getId());
			deploymentList.setTaskName(task.getName());
			deploymentList.setProcInsId(query.taskId(task.getId()).singleResult().getProcessInstanceId());
			deploymentList.setProcDefId(query.taskId(task.getId()).singleResult().getProcessDefinitionId());
			//#流程定义表
			ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(deploymentList.getProcDefId()).singleResult();

			deploymentList.setProcdefName(processDefinition.getName());
			deploymentList.setProcdefKey(processDefinition.getKey());

			String processInstanceId = task.getProcessInstanceId();
			ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
					.processInstanceId(processInstanceId)//使用流程实例ID查询
					.singleResult();//单个对象
			String buniness_key = pi.getBusinessKey();

			if(StringUtils.isNotBlank(buniness_key)){
				//截取字符串，取buniness_key小数点的第2个值
				String businessType = buniness_key.split(":")[0];
				String businessId = buniness_key.split(":")[1];
				deploymentList.setBusinessType(businessType);
				deploymentList.setBusinessId(businessId);
			}

			//查贸易流程变量
			Map object  = (Map) runtimeService.getVariable(task.getExecutionId(),"irptKey");
			if(object!=null){
				deploymentList.setBbq(object.get("bbq").toString());
				deploymentList.setUserCreditCode(object.get("userCreditCode").toString());
				deploymentList.setStartTime(object.get("startTime").toString());
				deploymentList.setStarter(object.get("orgName").toString());
				deploymentList.setUserName(object.get("userName").toString());
				deploymentList.setOrgName(object.get("orgName").toString());
				deploymentList.setAreaCode(object.get("areaCode").toString());
			}
			//转换时间
			String assignTime=DateUtil.getDateFormat(task.getCreateTime(), DateUtil.df);
			deploymentList.setAssignTime(assignTime);
			deploymentList.setUserTaskType("20");
			if(StringUtils.isNotEmpty(deploymentList.getAreaCode())){
				if(deploymentList.getAreaCode().contains(areaCode)){
					deploymentLists.add(deploymentList);
				}
			}
		}
		return deploymentLists;
	}


	public List<HistoryApprovalList> historic(String key,String userId, Integer pageNum, Integer pageSize) {
		new PageResponse().enablePage(pageNum, pageSize);
		HistoricTaskInstanceQuery histTaskQuery = historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%" + userId + "%").finished()
				.includeProcessVariables().orderByHistoricTaskInstanceEndTime().desc();
		if(key!=null||!"".equals(key)) {
			histTaskQuery.processDefinitionKey(key);
		}

		List<HistoricTaskInstance> list = histTaskQuery.list();
		List<HistoryApprovalList> historyLists = new ArrayList<HistoryApprovalList>();
		for(HistoricTaskInstance historicTaskInstance : list) {
			HistoryApprovalList historyList = new HistoryApprovalList();
			historyList.setActivityName(historicTaskInstance.getName());
			historyList.setProcInsId(historicTaskInstance.getProcessInstanceId());
			historyList.setApproveDate(historicTaskInstance.getEndTime());
			historyLists.add(historyList);
		}


		return historyLists;
	}


	/**
	 * 获取已办列表---不分页
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List<HistoryApprovalVO> findByAlreadyDoneoPage(String userId) {
		HistoricTaskInstanceQuery histTaskQuery = historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%" + userId + "%").finished()
				.includeProcessVariables().orderByHistoricTaskInstanceEndTime().desc();
		List<HistoricTaskInstance> list = histTaskQuery.list();
		List<HistoryApprovalVO> historyLists = new ArrayList<HistoryApprovalVO>();
		for(HistoricTaskInstance historicTaskInstance: list) {
			HistoryApprovalVO historyList = new HistoryApprovalVO();
			historyList.setActivityName(historicTaskInstance.getName());
			historyList.setProcInsId(historicTaskInstance.getProcessInstanceId());
			String approveDate=DateUtil.getDateFormat(historicTaskInstance.getEndTime(), DateUtil.df);
			historyList.setApproveDate(approveDate);
			historyList.setTaskId(historicTaskInstance.getId());
			//#流程定义表
			ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(historicTaskInstance.getProcessDefinitionId()).singleResult();

			historyList.setProcdefName(processDefinition.getName());
			historyList.setProcdefKey(processDefinition.getKey());

			String processInstanceId = historyList.getProcInsId();
			HistoricProcessInstance hi= historyService.createHistoricProcessInstanceQuery()
					.processInstanceId(processInstanceId)//使用流程实例ID查询
					.singleResult();//单个对象
			String buniness_key = hi.getBusinessKey();
			if(StringUtils.isNotBlank(buniness_key)){
				//截取字符串，取buniness_key小数点的第2个值
				String businessType = buniness_key.split(":")[0];
				String businessId = buniness_key.split(":")[1];
				historyList.setBusinessType(businessType);
				historyList.setBusinessId(businessId);
			}

			//查贸易流程变量
			Map object = (Map) this.getHisVariable(historicTaskInstance.getProcessInstanceId(), "irptKey");
			if(object!=null){
				historyList.setBbq(object.get("bbq").toString());
				historyList.setUserCreditCode(object.get("userCreditCode").toString());
				historyList.setStartTime(object.get("startTime").toString());
				historyList.setStarter(object.get("orgName").toString());
				historyList.setUserName(object.get("userName").toString());
				historyList.setOrgName(object.get("orgName").toString());
				historyList.setAreaCode(object.get("areaCode").toString());
			}
			//转换时间
			String startTime=DateUtil.getDateFormat(historicTaskInstance.getCreateTime(), DateUtil.df);
			historyList.setStartTime(startTime);
			//转换时间
			String endTime=DateUtil.getDateFormat(historicTaskInstance.getEndTime(), DateUtil.df);
			historyList.setEndTime(endTime);

			historyLists.add(historyList);
		}
		return historyLists;
	}


	/**
	 * 获取历史流程变量
	 * @param processInstanceId
	 * @param key
	 * @return
	 */
	public Object getHisVariable(String processInstanceId,String key) {
		Object variable = null;
		List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list();
		for (int i = 0; i < list.size(); i++) {
			HistoricVariableInstance historicVariableInstance = list.get(i);
			if (historicVariableInstance.getVariableName().equals(key)) {
				variable = historicVariableInstance.getValue();
			}
		}

		return variable;

	}


	/**
	 * 获取批注信息，传递的是当前任务ID，获取历史任务ID对应的批注
	 * @param processId
	 * @return
	 */
	public List<HistoryList> processInfo(String processId) {
		List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(processId)
				.orderByHistoricActivityInstanceStartTime().asc().orderByHistoricActivityInstanceEndTime().desc().list();
		
		List<HistoryList> historyList=new ArrayList<HistoryList>();
		for (HistoricActivityInstance historicActivityInstance: list){
			HistoryList history = new HistoryList();
//			history.setAssigneeName(historicActivityInstance.getAssignee());
			//转换时间
			String startTime=DateUtil.getDateFormat(historicActivityInstance.getStartTime(), DateUtil.df);
			history.setStartTime(startTime);
			history.setActivityName(historicActivityInstance.getActivityName());
			List<Comment> comments = taskService.getTaskComments(historicActivityInstance.getTaskId());
			if(comments.size()>0) {
				//截取数据
				String[] event=comments.get(0).getUserId().split("--");
				history.setAssigneeName(event[0]);
				history.setEvent(event[1]);
				history.setComment(comments.get(0).getFullMessage());
				//转换时间
				String endTime=DateUtil.getDateFormat(comments.get(0).getTime(), DateUtil.df);
				history.setEndDate(endTime);
				history.setUserType("no");
				historyList.add(history);
			}
		}

		//根据流程ID 判断流程 是否结束
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
		if(pi!=null){
			Task singleResult = taskService.createTaskQuery().processInstanceId(processId).singleResult();
			if(StringUtils.isNotEmpty(singleResult.getAssignee())){
				HistoryList history = new HistoryList();
				String startTime=DateUtil.getDateFormat(singleResult.getCreateTime(), DateUtil.df);
				history.setStartTime(startTime);
				history.setActivityName(singleResult.getName());
				history.setAssigneeName(singleResult.getAssignee());
				history.setEvent("办理中");
				history.setComment("--");
				//转换时间
				history.setEndDate("--");
				history.setUserType("yes");
				historyList.add(history);
			}else{
				//查贸易流程变量
				Map object  = (Map) runtimeService.getVariable(singleResult.getExecutionId(),"irptKey");
				String areaCode="";
				if(object!=null){
					 areaCode= object.get("areaCode").toString();
				}
				//根据当前任务Id查询角色 processDefinitionId
				String groupName=getTaskGroupName(singleResult.getId());
				if (StringUtils.isNotEmpty(groupName)) {
					List<User> listUser = identityService.createUserQuery().memberOfGroup(groupName).list();
					StringBuffer sb = new StringBuffer();
					for (User user : listUser) {
						if (areaCode.contains(user.getEmail())) {
							sb.append(user.getFirstName()).append(",");
						}
					}

				if(sb.length()>0){
					String assigneeName=sb.substring(0, sb.length() - 1);
					HistoryList history = new HistoryList();
					String startTime=DateUtil.getDateFormat(singleResult.getCreateTime(), DateUtil.df);
					history.setStartTime(startTime);
					history.setActivityName(singleResult.getName());
					history.setAssigneeName(assigneeName);
					history.setEvent("办理中");
					history.setComment("--");
					//转换时间
					history.setEndDate("--");
					history.setUserType("no");
					historyList.add(history);
				}
				}
			}
		}

		return historyList;
	}
	
	
	public List<HistoryList> processInfos(String processId) {
		List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(processId)
				.orderByHistoricActivityInstanceStartTime().asc().orderByHistoricActivityInstanceEndTime().desc().list();
		
		List<HistoryList> historyList=new ArrayList<HistoryList>();
		for (HistoricActivityInstance historicActivityInstance: list){
			HistoryList history = new HistoryList();
			history.setAssigneeName(historicActivityInstance.getAssignee());
			//转换时间
			String startTime=DateUtil.getDateFormat(historicActivityInstance.getStartTime(), DateUtil.df);
			history.setStartTime(startTime);
			history.setActivityName(historicActivityInstance.getActivityName());
			List<Comment> comments = taskService.getTaskComments(historicActivityInstance.getTaskId());
			if(comments.size()>0) {
				history.setComment(comments.get(0).getFullMessage());
				//转换时间
				String endTime=DateUtil.getDateFormat(comments.get(0).getTime(), DateUtil.df);
				history.setEndDate(endTime);
				historyList.add(history);
			}
		}
		return historyList;
	}


	/**
	 * 根据当前任务Id查询角色
	 * @param taskId
	 * @return
	 */
	private String getTaskGroupName(String taskId) {
		String name="";
		List<IdentityLink> links = taskService.getIdentityLinksForTask(taskId);
		for(IdentityLink identityLink:links){
			if(identityLink.getUserId()!=null){
				name=identityLink.getUserId();
				return name;
			}
			if(identityLink.getGroupId()!=null){
				name=identityLink.getGroupId();
				return name;
			}
		}
		return null;
	}


	/**
	 *添加流程变量
	 * @param values
	 * @return
	 */
	public int setVariableByTask(
			String values,
			String processId
	) {
		System.out.println("=============添加流程变量 start=====================");
		System.out.println("流程ID :processId="+processId);
		System.out.println("流程变量:values ="+values);
		Map<String, Object> variable=JSON.parseObject(values);
		System.out.println("流程变量转为Map : variable ="+variable);
		System.out.println("=============添加流程变量 end=====================");
		Task singleResult = taskService.createTaskQuery().processInstanceId(processId).singleResult();
		runtimeService.setVariableLocal(singleResult.getExecutionId(), "irptKey", variable);


		return 1;
	}

	/**
	 * 查询待办任务明细
	 * @param taskId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Map> findOutComeListByTaskId(String taskId) {
		//返回存放连线的名称集合
		List<Map> list = new ArrayList<Map>();
		//1:使用任务ID，查询任务对象
		Task task = taskService.createTaskQuery()//
				.taskId(taskId)//使用任务ID查询
				.singleResult();
		//3：查询ProcessDefinitionEntiy对象
		ExecutionEntity ee = (ExecutionEntity) runtimeService.createExecutionQuery()
				.executionId(task.getExecutionId()).singleResult();
		//获取当前活动的id
		String crruentActivityId = ee.getActivityId();

		//4：获取当前的活动
		BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
		FlowNode flowNode = (FlowNode) bpmnModel.getFlowElement(crruentActivityId);

		//5：获取当前活动完成之后连线的名称
		List<SequenceFlow> outFlows = flowNode.getOutgoingFlows();

		if(outFlows!=null && outFlows.size()>0){
			for(SequenceFlow pvm:outFlows) {
				String name = pvm.getName();
				if(StringUtils.isNotBlank(name)){
					Map map=new HashMap();
					map.put("button",name);
					list.add(map);
				}
				else{
					Map map=new HashMap();
					map.put("button", "提交");
					list.add(map);
				}
			}
		}


		return list;
	}

	public int delete(String processId) {
		try {
			runtimeService.deleteProcessInstance(processId,"用户取消");
		} catch (Exception e) {
			return 0;
		}
		return 1;
	}

	public Object getVariableByTask(String values, String processId) {
		Object variable = null;
        List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(processId).list();
        for (int i = 0; i < list.size(); i++) {
            HistoricVariableInstance historicVariableInstance = list.get(i);
            if (historicVariableInstance.getVariableName().equals(values)) {
                variable = historicVariableInstance.getValue();
            }
        }
 
        return variable;
	}

	public int setvariable(String key, Object value, String processId) {

		Task singleResult = taskService.createTaskQuery().processInstanceId(processId).singleResult();
		runtimeService.setVariableLocal(singleResult.getExecutionId(), key, value);


		return 1;
	}

	public List<HistoryList> bussinessId(String bussinessId) {
		String processId = "";
		
		//根据流程ID 判断流程 是否结束
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(bussinessId).singleResult();
		if(pi==null){
			HistoricProcessInstance historicProcessInstance =  historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(bussinessId).singleResult();
			processId = historicProcessInstance.getId();
		} else {
			processId = pi.getProcessInstanceId();
		}
		
		
		
		
		List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(processId)
				.orderByHistoricActivityInstanceStartTime().asc().orderByHistoricActivityInstanceEndTime().desc().list();
		
		List<HistoryList> historyList=new ArrayList<HistoryList>();
		for (HistoricActivityInstance historicActivityInstance: list){
			HistoryList history = new HistoryList();
//			history.setAssigneeName(historicActivityInstance.getAssignee());
			//转换时间
			String startTime=DateUtil.getDateFormat(historicActivityInstance.getStartTime(), DateUtil.df);
			history.setStartTime(startTime);
			history.setActivityName(historicActivityInstance.getActivityName());
			List<Comment> comments = taskService.getTaskComments(historicActivityInstance.getTaskId());
			if(comments.size()>0) {
				//截取数据
				history.setComment(comments.get(0).getFullMessage());
				//转换时间
				String endTime=DateUtil.getDateFormat(comments.get(0).getTime(), DateUtil.df);
				history.setEndDate(endTime);
				history.setUserType("no");
				
				User user = identityService.createUserQuery().userId(historicActivityInstance.getAssignee()).singleResult();
				if(user!=null) {
					history.setAssigneeName(user.getFirstName());
				}
				historyList.add(history);
			}
			
		}

		
//		if(pi!=null){
//			Task singleResult = taskService.createTaskQuery().processInstanceId(processId).singleResult();
//			if(StringUtils.isNotEmpty(singleResult.getAssignee())){
//				HistoryList history = new HistoryList();
//				String startTime=DateUtil.getDateFormat(singleResult.getCreateTime(), DateUtil.df);
//				history.setStartTime(startTime);
//				history.setActivityName(singleResult.getName());
//				history.setAssigneeName(singleResult.getAssignee());
//				history.setEvent("办理中");
//				history.setComment("--");
//				//转换时间
//				history.setEndDate("--");
//				history.setUserType("yes");
//				historyList.add(history);
//			}else{
//				//查贸易流程变量
//				Map object  = (Map) runtimeService.getVariable(singleResult.getExecutionId(),"irptKey");
//				String areaCode="";
//				if(object!=null){
//					 areaCode= object.get("areaCode").toString();
//				}
//				//根据当前任务Id查询角色 processDefinitionId
//				String groupName=getTaskGroupName(singleResult.getId());
//				if (StringUtils.isNotEmpty(groupName)) {
//					List<User> listUser = identityService.createUserQuery().memberOfGroup(groupName).list();
//					StringBuffer sb = new StringBuffer();
//					for (User user : listUser) {
//						if (areaCode.contains(user.getEmail())) {
//							sb.append(user.getFirstName()).append(",");
//						}
//					}
//
//				if(sb.length()>0){
//					String assigneeName=sb.substring(0,sb.length()-1);
//					HistoryList history = new HistoryList();
//					String startTime=DateUtil.getDateFormat(singleResult.getCreateTime(), DateUtil.df);
//					history.setStartTime(startTime);
//					history.setActivityName(singleResult.getName());
//					history.setAssigneeName(assigneeName);
//					history.setEvent("办理中");
//					history.setComment("--");
//					//转换时间
//					history.setEndDate("--");
//					history.setUserType("no");
//					historyList.add(history);
//				}
//				}
//			}
//		}

		return historyList;
	}

	public int completeTask(FlowTodoVO completeVO) {
		Map<String, Object> vars = Maps.newHashMap();
		//获取流程当前节点
		Task singleResult = null;
		if(StringUtils.isEmpty(completeVO.getProcessId())) {//根据业务key键查询任务信息
			singleResult = taskService.createTaskQuery().processInstanceBusinessKey(completeVO.getBusinessInfo()).singleResult();
		} else {//根据流程id查询业务信息
			singleResult = taskService.createTaskQuery().processInstanceId(completeVO.getProcessId()).singleResult();
		}
		
		if(singleResult==null) {
			return 0;
		}

		//获取流程的任务id
		String taskId = singleResult.getId();
		if(StringUtils.isNotEmpty(completeVO.getMessage())){
			taskService.addComment(taskId, completeVO.getProcessId(), completeVO.getMessage());//添加审批建议
		}
		//添加审批人
		taskService.setAssignee(taskId, completeVO.getUserId());
		//设置参数
		vars.put(completeVO.getStatusKey(), completeVO.getStatus());//设置审批状态
		if(StringUtils.isNotEmpty(completeVO.getStatusName())) {

			vars.put("statusName", completeVO.getStatusName());//设置审批状态
		}
		//提交审批
		taskService.complete(taskId, vars);
		return 1;
	}

	public Object getVariableByBusiness(String value, String bussinessId) {
		Object variable = null;
		HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(bussinessId).includeProcessVariables().singleResult();
		Map<String, Object> map = processInstance.getProcessVariables();
//		List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId().list();
//        for (int i = 0; i < list.size(); i++) {
//            HistoricVariableInstance historicVariableInstance = list.get(i);
//            if (historicVariableInstance.getVariableName().equals(value)) {
//                variable = historicVariableInstance.getValue();
//            }
//        }
		variable = map.get(value);
        return variable;
	}

	public TaskStatus taskInfo(String userId, String bussinessId) {
		TaskStatus taskStatus = new TaskStatus();
		taskStatus.setSfxssh(0);
		try {
			List<String> id = new ArrayList<String>();
			List<Group> groups =  identityService.createGroupQuery().groupMember(userId).list();
			for(Group group:groups) {
				id.add(group.getId());
			}
			taskStatus.setSfxssh(taskService.createTaskQuery().taskAssigneeIds(id).processInstanceBusinessKey(bussinessId).list().size());
			taskStatus.setStatus(getVariableByBusiness("status",bussinessId).toString());
			taskStatus.setStatusName(getVariableByBusiness("statusName",bussinessId).toString());
		} catch (Exception e) {
			return taskStatus;
		}
		return taskStatus;
		
	}



}
