package com.unis.flowable.server.service;

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

import org.apache.commons.lang.StringUtils;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
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 org.springframework.util.ObjectUtils;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.unis.common.utils.CurrentUtil;
import com.unis.common.utils.DateUtil;
import com.unis.common.utils.ResponseWrapper;
import com.unis.flowable.common.vo.DeploymentVO;
import com.unis.flowable.common.vo.FlowTodoQuerVO;
import com.unis.flowable.common.vo.FlowTodoVO;
import com.unis.flowable.common.vo.HistoryApprovalList;
import com.unis.flowable.common.vo.StartTodoVO;
import com.unis.flowable.server.config.PageResponse;
import com.unis.flowable.server.config.PageResult;


@Service
public class FlowTodoService{
	
	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private IdentityService identityService;


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

	@Autowired
	private RepositoryService repositoryService;
	
	
	public ResponseWrapper startNewTodo(StartTodoVO startTodoVO) {
		try {
			//设置流程启动人
			identityService.setAuthenticatedUserId(CurrentUtil.getUserId());
			Map<String, Object> variables = new HashMap<String,Object>();
			//添加用户跟审批状态
			variables.put("userId", CurrentUtil.getUserId());
			variables.put("status", "1");
			//拼接流程业务key
			String processId = startTodoVO.getBusinessType()+":"+startTodoVO.getId();
			//开启新流程
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("YWXTDBXX",processId,variables);
			if(processInstance==null) {
				return ResponseWrapper.error();
			}
			Task singleResult = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
			if(singleResult==null) {
				return ResponseWrapper.error();
			}
			if(!singleResult.getAssignee().contains(CurrentUtil.getUserId())) {
				return ResponseWrapper.error("当前用户无权限审批！");
			}
			
			//获取流程的任务id
			String taskId = singleResult.getId();
			if(!startTodoVO.getMessage().equals(""))
				taskService.addComment(taskId, processInstance.getProcessInstanceId(), startTodoVO.getMessage());//添加审批建议
			//添加审批人
			taskService.setAssignee(taskId, CurrentUtil.getUserId());
			//设置参数
			variables.put("userId", startTodoVO.getRoleId());//设置下级审批人，设置业务名称
			variables.put("status", "1");//设置下级审批人，设置业务名称
			variables.put("businessName", startTodoVO.getBusinessName());//业务名称
			variables.put("completeStatus", startTodoVO.getCompleteStatus());//提交状态
			//设置组织编号//组织名称
			variables.put("orgCode", CurrentUtil.getOrgId());
			variables.put("orgName", CurrentUtil.getOrgName());
			variables.put("businessTypeName", startTodoVO.getBusinessTypeName());
			variables.put("companyName", startTodoVO.getCompanyName());
			//提交审批
			taskService.complete(taskId, variables);
			return ResponseWrapper.success(processInstance.getProcessInstanceId());
		} catch (Exception e) {
			return ResponseWrapper.error("流程异常，已终止！");
		}
		
	}

	/**
	 * 审批
	 * @param completeVO
	 * @return
	 */
	public int complete(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;
		}
		//区分用户或者部门某人审批
//		if(!singleResult.getAssignee().contains(CurrentUtil.getUserId())//用户
//				||!singleResult.getAssignee().contains(CurrentUtil.getDeptId())) {//部门
//			return -1;
//		}

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


	public PageResult<HistoryApprovalList> historic(FlowTodoQuerVO flowTodoQuerVO, Integer pageNum, Integer pageSize) {
		HistoricTaskInstanceQuery histTaskQuery = historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%" + CurrentUtil.getUserId() + "%");
		if(StringUtils.isNotEmpty(flowTodoQuerVO.getBusinessName())) {//业务名称
			histTaskQuery.processVariableValueLike("businessName", "%"+flowTodoQuerVO.getBusinessName()+"%");
		}
		if(StringUtils.isNotEmpty(flowTodoQuerVO.getBusinessTypeName())) {//业务名称
			histTaskQuery.processVariableValueLike("businessTypeName", "%"+flowTodoQuerVO.getBusinessTypeName()+"%");
		}
		if(StringUtils.isNotEmpty(flowTodoQuerVO.getCompanyName())) {//企业名称
			histTaskQuery.processVariableValueLike("companyName", "%"+flowTodoQuerVO.getCompanyName()+"%");
		}
		if(flowTodoQuerVO.getStartDate()!=null) {//开始时间
			histTaskQuery.taskCreatedAfter(flowTodoQuerVO.getStartDate());
		}
		if(flowTodoQuerVO.getEndDate()!=null) {//结束时间
			histTaskQuery.taskCreatedBefore(flowTodoQuerVO.getEndDate());
		}
		List<HistoricTaskInstance> list = histTaskQuery.includeProcessVariables().orderByTaskDueDate().desc().listPage((pageNum - 1) * pageSize, pageSize);
		List<HistoryApprovalList> historyLists = new ArrayList<HistoryApprovalList>();
		for(HistoricTaskInstance historicTaskInstance : list) {
			HistoryApprovalList historyList = new HistoryApprovalList();
			historyList.setActivityName(historicTaskInstance.getName());
			historyList.setProcInsId(historicTaskInstance.getProcessInstanceId());
			HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(historicTaskInstance.getProcessInstanceId()).singleResult();
			historyList.setApproveDate(historicTaskInstance.getEndTime());
			Map<String, Object> map = historicTaskInstance.getProcessVariables();
			historyList.setBusinessName((String)map.get("businessName"));//业务名称
			historyList.setCompleteStatus((String)map.get("completeStatus"));//审批状态
			historyList.setBusinessTypeName((String)map.get("businessTypeName"));//业务类型名称
			historyList.setBusinessType((String)map.get("businessType"));//审批状态
			
			if(StringUtils.isNotEmpty(historicProcessInstance.getBusinessKey())) {//业务类型不为null
				String[] businesss = historicProcessInstance.getBusinessKey().split(":");
				historyList.setBusinessType(businesss[0]);
				historyList.setBusinessId(businesss[1]);
			}
			
			historyList.setOrgName((String)map.get("orgName"));//组织名称
			historyList.setCompanyName((String)map.get("companyName"));//企业名称
			String userId = (String) map.get("userId");
			if(org.apache.commons.lang3.StringUtils.isNoneEmpty(userId)) {
				User user =  identityService.createUserQuery().userId(userId).singleResult();
				if(user!=null) {
					historyList.setUserName(user.getFirstName());//userName办结人
				}
			}
			historyLists.add(historyList);
		}
		return new PageResult<HistoryApprovalList>(histTaskQuery.count(), historyLists);
	}

	public List<DeploymentVO> getUserTaskNoPage(FlowTodoQuerVO flowTodoQuerVO) {

		List<DeploymentVO> deploymentLists = new ArrayList<DeploymentVO>();
		deploymentLists.addAll(getUserTaskNoPageUser(flowTodoQuerVO));
		List<String> id = new ArrayList<String>();
		List<Group> groups =  identityService.createGroupQuery().groupMember(CurrentUtil.getUserId()).list();
		for(Group group:groups) {
			id.add(group.getId());
		}
		if(id.size()>0) {
			deploymentLists.addAll(getUserTaskNoPageUser(id,flowTodoQuerVO));
		}
		return deploymentLists;
	}

	public PageResult<DeploymentVO> getUserTaskPage(FlowTodoQuerVO flowTodoQuerVO, Integer pageNum, Integer pageSize) {
		// 模糊查询该审批人所需要审批的任务
		TaskQuery query = taskService.createTaskQuery();

		if (StringUtils.isNotEmpty(flowTodoQuerVO.getBusinessName())) {// 业务名称
			query.processVariableValueLike("businessName", "%" + flowTodoQuerVO.getBusinessName() + "%");
		}
		if (StringUtils.isNotEmpty(flowTodoQuerVO.getCompleteStatus())) {// 业务状态
			query.processVariableValueLike("completeStatus", "%" + flowTodoQuerVO.getCompleteStatus() + "%");
		}
		if (flowTodoQuerVO.getStartDate() != null) {// 开始时间
			query.taskCreatedAfter(flowTodoQuerVO.getStartDate());
		}
		if (flowTodoQuerVO.getEndDate() != null) {// 结束时间
			query.taskCreatedBefore(flowTodoQuerVO.getEndDate());
		}
		query.taskAssigneeLike("%" + CurrentUtil.getUserId() + "%");

		/*List<Group> groups = identityService.createGroupQuery().groupMember(CurrentUtil.getUserId()).list();
		for (Group group : groups) {// 查询组任务
			query.or().taskAssignee(group.getId()).endOr();
		}*/
		/*if(groups.size()>0){
			List<String> list=new ArrayList<>();
			for (Group group : groups) {// 查询组任务
				list.add(group.getId());
			}
			query.taskAssigneeIds(list);
		}*/
		query.orderByTaskCreateTime().desc();
		long total = query.count();
		List<Task> tasks = query.listPage((pageNum - 1) * pageSize, pageSize);
		List<DeploymentVO> deploymentLists = new ArrayList<DeploymentVO>();
		for (Task task : tasks) {
			DeploymentVO deploymentList = new DeploymentVO();
			deploymentList.setTaskId(task.getId());
			deploymentList.setTaskName(task.getName());
			// 根据流程id获取流程变量
			List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery()
					.processInstanceId(task.getProcessInstanceId()).list();
			for (HistoricVariableInstance historicVariableInstance : list) {
				if (historicVariableInstance.getVariableName().equals("businessName")) {
					deploymentList.setBusinessName((String) historicVariableInstance.getValue());// 业务名称
				} else if (historicVariableInstance.getVariableName().equals("completeStatus")) {
					deploymentList.setCompleteStatus((String) historicVariableInstance.getValue());// 审批状态
				} else if (historicVariableInstance.getVariableName().equals("businessTypeName")) {
					deploymentList.setBusinessTypeName((String) historicVariableInstance.getValue());// 审批状态
				} else if (historicVariableInstance.getVariableName().equals("orgName")) {
					deploymentList.setOrgName((String) historicVariableInstance.getValue());// 审批状态
				} else if (historicVariableInstance.getVariableName().equals("companyName")) {
					deploymentList.setCompanyName((String) historicVariableInstance.getValue());// 审批状态
				}
			}
			Task taskResult = query.taskId(task.getId()).singleResult();
			if(!ObjectUtils.isEmpty(taskResult)) {
				deploymentList.setProcInsId(taskResult.getProcessInstanceId());
				deploymentList.setProcDefId(taskResult.getProcessDefinitionId());
			}
			// #流程定义表
			ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(task.getProcessDefinitionId()).singleResult();

			ProcessInstance instance = runtimeService.createProcessInstanceQuery()
					.processInstanceId(task.getProcessInstanceId()).singleResult();
			deploymentList.setBusinessKey(instance.getBusinessKey());
			if (StringUtils.isNotEmpty(instance.getBusinessKey())) {// 业务类型不为null
				String[] businesss = instance.getBusinessKey().split(":");
				deploymentList.setBusinessType(businesss[0]);
				deploymentList.setBusinessId(businesss[1]);
			}
			deploymentList.setProcdefName(processDefinition.getName());
			deploymentList.setProcdefKey(processDefinition.getKey());

			// 查贸易流程变量
			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 new PageResult<DeploymentVO>(total, deploymentLists);
	}
	
	
	public List<DeploymentVO> getUserTaskNoPageUser(FlowTodoQuerVO flowTodoQuerVO) {

		List<DeploymentVO> deploymentLists = new ArrayList<DeploymentVO>();
		//模糊查询该审批人所需要审批的任务
		TaskQuery query = taskService.createTaskQuery().taskAssigneeLike("%" + CurrentUtil.getUserId() + "%");
		

		if(StringUtils.isNotEmpty(flowTodoQuerVO.getBusinessName())) {//业务名称
			query.processVariableValueLike("businessName", "%"+flowTodoQuerVO.getBusinessName()+"%");
		}
		if(StringUtils.isNotEmpty(flowTodoQuerVO.getCompleteStatus())) {//业务状态
			query.processVariableValueLike("completeStatus", "%"+flowTodoQuerVO.getCompleteStatus()+"%");
		}
		if(flowTodoQuerVO.getStartDate()!=null) {//开始时间
			query.taskCreatedAfter(flowTodoQuerVO.getStartDate());
		}
		if(flowTodoQuerVO.getEndDate()!=null) {//结束时间
			query.taskCreatedBefore(flowTodoQuerVO.getEndDate());
		}
		query.orderByTaskCreateTime().desc();
		List<Task> tasks = query.list();
		for(Task task:tasks) {
			DeploymentVO deploymentList = new DeploymentVO();
			deploymentList.setTaskId(task.getId());
			deploymentList.setTaskName(task.getName());
			//根据流程id获取流程变量
			List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(task.getProcessInstanceId()).list();
			for(HistoricVariableInstance historicVariableInstance:list) {
				if(historicVariableInstance.getVariableName().equals("businessName")) {
					deploymentList.setBusinessName((String)historicVariableInstance.getValue());//业务名称
				} else if(historicVariableInstance.getVariableName().equals("completeStatus")) {
					deploymentList.setCompleteStatus((String)historicVariableInstance.getValue());//审批状态
				} else if(historicVariableInstance.getVariableName().equals("businessTypeName")) {
					deploymentList.setBusinessTypeName((String)historicVariableInstance.getValue());//审批状态
				} else if(historicVariableInstance.getVariableName().equals("orgName")) {
					deploymentList.setOrgName((String)historicVariableInstance.getValue());//审批状态
				} else if(historicVariableInstance.getVariableName().equals("companyName")) {
					deploymentList.setCompanyName((String)historicVariableInstance.getValue());//审批状态
				}
			}
			deploymentList.setProcInsId(query.taskId(task.getId()).singleResult().getProcessInstanceId());
			deploymentList.setProcDefId(query.taskId(task.getId()).singleResult().getProcessDefinitionId());
			//#流程定义表
			ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(task.getProcessDefinitionId()).singleResult();
			
			
			ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
			deploymentList.setBusinessKey(instance.getBusinessKey());
			if(StringUtils.isNotEmpty(instance.getBusinessKey())) {//业务类型不为null
				String[] businesss = instance.getBusinessKey().split(":");
				deploymentList.setBusinessType(businesss[0]);
				deploymentList.setBusinessId(businesss[1]);
			}
			deploymentList.setProcdefName(processDefinition.getName());
			deploymentList.setProcdefKey(processDefinition.getKey());

			//查贸易流程变量
			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;
	}
	
	
	
	public List<DeploymentVO> getUserTaskNoPageUser(List<String> ids,FlowTodoQuerVO flowTodoQuerVO) {

		List<DeploymentVO> deploymentLists = new ArrayList<DeploymentVO>();
		//模糊查询该审批人所需要审批的任务
		TaskQuery query = taskService.createTaskQuery().taskAssigneeIds(ids);
		

		if(StringUtils.isNotEmpty(flowTodoQuerVO.getBusinessName())) {//业务名称
			query.processVariableValueLike("businessName", "%"+flowTodoQuerVO.getBusinessName()+"%");
		}
		if(StringUtils.isNotEmpty(flowTodoQuerVO.getCompleteStatus())) {//业务状态
			query.processVariableValueLike("completeStatus", "%"+flowTodoQuerVO.getCompleteStatus()+"%");
		}
		if(flowTodoQuerVO.getStartDate()!=null) {//开始时间
			query.taskCreatedAfter(flowTodoQuerVO.getStartDate());
		}
		if(flowTodoQuerVO.getEndDate()!=null) {//结束时间
			query.taskCreatedBefore(flowTodoQuerVO.getEndDate());
		}
		query.orderByTaskCreateTime().desc();
		List<Task> tasks = query.list();
		for(Task task:tasks) {
			DeploymentVO deploymentList = new DeploymentVO();
			deploymentList.setTaskId(task.getId());
			deploymentList.setTaskName(task.getName());
			//根据流程id获取流程变量
			List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(task.getProcessInstanceId()).list();
			for(HistoricVariableInstance historicVariableInstance:list) {
				if(historicVariableInstance.getVariableName().equals("businessName")) {
					deploymentList.setBusinessName((String)historicVariableInstance.getValue());//业务名称
				} else if(historicVariableInstance.getVariableName().equals("completeStatus")) {
					deploymentList.setCompleteStatus((String)historicVariableInstance.getValue());//审批状态
				} else if(historicVariableInstance.getVariableName().equals("businessTypeName")) {
					deploymentList.setBusinessTypeName((String)historicVariableInstance.getValue());//审批状态
				} else if(historicVariableInstance.getVariableName().equals("orgName")) {
					deploymentList.setOrgName((String)historicVariableInstance.getValue());//审批状态
				} else if(historicVariableInstance.getVariableName().equals("companyName")) {
					deploymentList.setCompanyName((String)historicVariableInstance.getValue());//审批状态
				}
			}
			deploymentList.setProcInsId(query.taskId(task.getId()).singleResult().getProcessInstanceId());
			deploymentList.setProcDefId(query.taskId(task.getId()).singleResult().getProcessDefinitionId());
			//#流程定义表
			ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(task.getProcessDefinitionId()).singleResult();
			
			
			ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
			deploymentList.setBusinessKey(instance.getBusinessKey());
			if(StringUtils.isNotEmpty(instance.getBusinessKey())) {//业务类型不为null
				String[] businesss = instance.getBusinessKey().split(":");
				deploymentList.setBusinessType(businesss[0]);
				deploymentList.setBusinessId(businesss[1]);
			}
			deploymentList.setProcdefName(processDefinition.getName());
			deploymentList.setProcdefKey(processDefinition.getKey());

			//查贸易流程变量
			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;
	}
}
