package com.unis.flowable.server.controller;


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

import com.github.pagehelper.PageInfo;
import com.unis.common.utils.ResponseWrapper;
import com.unis.flowable.common.vo.*;
import com.unis.flowable.server.service.FlowTaskService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;


@RestController
@RequestMapping("/task")
@Api(value= "FlowTaskController", description = "任务管理")
public class FlowTaskController {
	
	@Autowired
	private FlowTaskService flowTaskService;


	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "start", method = RequestMethod.POST)
	@ApiOperation(value="开始新的流程", notes = "开始新流程")
	public ResponseWrapper startNewTask(
			@RequestBody StartNewTaskVO startNewTaskVO
	){
		String processId = flowTaskService.startNewTask(startNewTaskVO);

		if(processId==null||processId.equals("")) {
			return ResponseWrapper.error(500,"开始新的流程启动失败",null);
		} else {
			Map result=new HashMap();
			result.put("processId",processId);
			return ResponseWrapper.success(200, "启动成功", result);
		}
	}
	
	@RequestMapping(value = "complete", method = RequestMethod.POST)
	@ApiOperation(value="审批", notes = "审批")
	public  ResponseWrapper complete(
			@RequestBody FlowAbleCompleteVO completeVO
	) {
		int result= flowTaskService.complete(completeVO);
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if(result==0) {
			return ResponseWrapper.error(500,"该流程已结束",null);
		} else if(result==-1) {
			return ResponseWrapper.error(500,"您不能审批此节点",null);
		} else {
			// 1 审核成功  2 流程结束
			modelMap.put("message", "审批成功");
			modelMap.put("data", completeVO.getProcessId());
			modelMap.put("result", result);
			return ResponseWrapper.success(200, "启动成功", modelMap);
		}
	}



	@RequestMapping(value = "completeGroup", method = RequestMethod.POST)
	@ApiOperation(value="审批并且分配组任务", notes = "审批并且分配组任务")
	public  ResponseWrapper completeGroup(
			@RequestBody CompleteGroupVO completeGroupVO
	) {
		int result= flowTaskService.completeGroup(completeGroupVO);
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if(result==0) {
			return ResponseWrapper.error(500,"该流程已结束",null);
		} else if(result==-1) {
			return ResponseWrapper.error(500,"您不能审批此节点",null);
		} else {
			modelMap.put("message", "审批成功");
			modelMap.put("data", completeGroupVO.getProcessId());
			modelMap.put("result", result);
			return ResponseWrapper.success(200, "启动成功", modelMap);
		}
	}



	@RequestMapping(value = "claim", method = RequestMethod.GET)
	@ApiOperation(value="拾取任务，将组任务分给个人任务", notes = "拾取任务，将组任务分给个人任务")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "taskId", value = "流程ID", paramType = "query"),
			@ApiImplicitParam(name = "userId", value = "用户id", paramType = "query")
	})
	public  ResponseWrapper claim(
			String taskId,
			String userId
	) {
		try {
			 flowTaskService.claim(taskId, userId);
			 return ResponseWrapper.success(200, "拾取任务成功",null);
		} catch (Exception e) {
 			e.printStackTrace();
			return ResponseWrapper.error(500, "拾取任务成功失败",null);
		}
	}



	@RequestMapping(value = "getUserTaskList", method = RequestMethod.GET)
	@ApiOperation(value="获取待办列表", notes = "待办列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "processId", value = "流程id", paramType = "query"),
		@ApiImplicitParam(name = "userId", value = "用户id", paramType = "query"),
		@ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query")
	})
	public PageInfo<DeploymentList> getUserTaskList(String processId,String userId,Integer pageNum, Integer pageSize){
		return new PageInfo<DeploymentList>(flowTaskService.getTaskUserList(processId,userId,pageNum,pageSize));
	}



	@RequestMapping(value = "getUserTaskNoPage", method = RequestMethod.GET)
	@ApiOperation(value="获取待办个人任务列表---不分页", notes = "待办列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", paramType = "query")
	})
	public ResponseWrapper getUserTaskNoPage(String userId){
		List<DeploymentVO> deploymentListList= flowTaskService.getUserTaskNoPage(userId);
		return ResponseWrapper.success(200, "查询成功", deploymentListList);
	}


	@RequestMapping(value = "getUserTaskGroupNoPage", method = RequestMethod.GET)
	@ApiOperation(value="获取待办任务组列表---不分页", notes = "待办列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", paramType = "query"),
			@ApiImplicitParam(name = "areaCode", value = "行政区划", paramType = "query")
	})
	public ResponseWrapper getUserTaskGroupNoPage(String userId,String areaCode){
		List<DeploymentVO> deploymentListList= flowTaskService.getUserTaskGroupNoPage(userId,areaCode);
		return ResponseWrapper.success(200, "查询成功", deploymentListList);
	}



	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "findByUserAndGroupTaskNoPage", method = RequestMethod.GET)
	@ApiOperation(value="获取待办个人任务和组任务合并列表---不分页", notes = "待办列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", paramType = "query"),
			@ApiImplicitParam(name = "areaCode", value = "行政区划", paramType = "query")
	})
	public ResponseWrapper findByUserAndGroupTaskNoPage(String userId,String areaCode){
		List<DeploymentVO> deploymentListList=new ArrayList();
		//组任务
		List<DeploymentVO> groupList= flowTaskService.getUserTaskGroupNoPage(userId,areaCode);
		deploymentListList.addAll(groupList);
		//个人任务
		List<DeploymentVO> userList= flowTaskService.getUserTaskNoPage(userId);
		deploymentListList.addAll(userList);
		return ResponseWrapper.success(200, "查询成功", deploymentListList);
	}








	@RequestMapping(value="historic", method=RequestMethod.GET)
	@ApiOperation(value="获取已办列表", notes = "已办列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "key", value = "流程key", paramType = "query"),
		@ApiImplicitParam(name = "userId", value = "userid", paramType = "query"),
		@ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query")
	})
	public PageInfo<HistoryApprovalList>  historic(String key,String userId,Integer pageNum, Integer pageSize) {
		return new  PageInfo<HistoryApprovalList>(flowTaskService.historic(key,userId,pageNum,pageSize));
		
	}


	@RequestMapping(value = "findByAlreadyDoneoPage", method = RequestMethod.GET)
	@ApiOperation(value="获取已办列表---不分页", notes = "获取已办列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", paramType = "query")
	})
	public ResponseWrapper findByAlreadyDoneoPage(String userId){
		List<HistoryApprovalVO> historyApprovalListList= flowTaskService.findByAlreadyDoneoPage(userId);
		return ResponseWrapper.success(200, "查询成功", historyApprovalListList);
	}



	
	@RequestMapping(value="findByProcessInfo", method=RequestMethod.GET)
	@ApiOperation(value="获取流程审批历史", notes = "审批历史信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "processId", value = "流程id", paramType = "query"),
	})
	public ResponseWrapper  findByProcessInfo(String processId) {
		List<HistoryList> deploymentLists = flowTaskService.processInfo(processId);
		return ResponseWrapper.success(200, "查询成功", deploymentLists);
		
	}
	
	
	@RequestMapping(value="processInfo", method=RequestMethod.GET)
	@ApiOperation(value="获取流程审批历史", notes = "审批历史信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "processId", value = "流程id", paramType = "query"),
	})
	public ResponseWrapper  processInfo(String processId) {
		List<HistoryList> deploymentLists = flowTaskService.processInfos(processId);
		return ResponseWrapper.success(200, "查询成功", deploymentLists);
		
	}



	@RequestMapping(value = "setVariableByTask", method = RequestMethod.GET)
	@ApiOperation(value="添加流程变量", notes = "添加流程变量")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "values", value = "变量 json 串", paramType = "query"),
			@ApiImplicitParam(name = "processId", value = "流程ID", paramType = "query")

	})
	public  ResponseWrapper setVariableByTask(String values,String processId) {
		int result= flowTaskService.setVariableByTask(values,processId);
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if(result==0) {
			return ResponseWrapper.error(500,"添加流程变量失败",null);
		} else if(result==-1) {
			return ResponseWrapper.error(500,"添加流程变量失败",null);
		} else {
			modelMap.put("message", "添加流程变量成功");
			return ResponseWrapper.success(200, "启动成功", modelMap);
		}
	}
	
	
	
	
	@RequestMapping(value = "variable", method = RequestMethod.POST)
	@ApiOperation(value="添加流程变量", notes = "添加流程变量")

	public  ResponseWrapper variable(@RequestBody VariableObject variableObject) {
		int result= flowTaskService.setvariable(variableObject.getKey(),variableObject.getValue(),variableObject.getProcessId());
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if(result==0) {
			return ResponseWrapper.error(500,"添加流程变量失败",null);
		} else if(result==-1) {
			return ResponseWrapper.error(500,"添加流程变量失败",null);
		} else {
			modelMap.put("message", "添加流程变量成功");
			return ResponseWrapper.success(200, "启动成功", modelMap);
		}
	}
	
	
	
	@RequestMapping(value = "variable", method = RequestMethod.GET)
	@ApiOperation(value="获取流程变量", notes = "获取流程变量")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "value", value = "变量 key键", paramType = "query"),
			@ApiImplicitParam(name = "processId", value = "流程ID", paramType = "query")

	})
	public  ResponseWrapper getVariableByTask(String value,String processId) {
		Object result= flowTaskService.getVariableByTask(value,processId);

			return ResponseWrapper.success(200, "获取成功", result);

	}


	/**
	 * 查询待办任务明细 --和审核信息
	 * @param taskId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@GetMapping(value = "/findByFormKeyByTaskId/{taskId}/{procInsId}")
	@ApiOperation(value="查询办理任务明细", notes = "查询办理任务明细")
	public ResponseWrapper findByFormKeyByTaskId(
			@PathVariable("taskId") String taskId,
			@PathVariable("procInsId") String procInsId

	) {
		try {
			Map map=new HashMap();
			List<Map> buttonList=flowTaskService.findOutComeListByTaskId(taskId);
			// 获取批注信息，传递的是当前任务ID，获取历史任务ID对应的批注
			List<HistoryList> commentList = flowTaskService.processInfo(procInsId);
			map.put("buttonList",buttonList);
			map.put("commentList",commentList);
			return ResponseWrapper.success(200, "查询成功", map);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.error(500, "活动信息查询失败",null);
		}
	}




	/**
	 * 查询已办办任务明细 --和审核信息
	 * @param taskId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@GetMapping(value = "/findByAlreadyDone/{taskId}/{procInsId}")
	@ApiOperation(value="查询办理任务明细", notes = "查询办理任务明细")
	public ResponseWrapper findByAlreadyDone(
			@PathVariable("taskId") String taskId,
			@PathVariable("procInsId") String procInsId

	) {
		try {
			Map map=new HashMap();
			// 获取批注信息，传递的是当前任务ID，获取历史任务ID对应的批注
			List<HistoryList> commentList = flowTaskService.processInfo(procInsId);
			map.put("commentList",commentList);
			return ResponseWrapper.success(200, "查询成功", map);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.error(500, "活动信息查询失败",null);
		}
	}

	@RequestMapping(value = "delete", method = RequestMethod.GET)
	@ApiOperation(value="删除启动的流程", notes = "删除流程")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "processId", value = "流程id", paramType = "query")
	})
	public ResponseWrapper delete(String processId){
		int  status = flowTaskService.delete(processId);

		if(status==0) {
			return ResponseWrapper.error(500,"删除失败",null);
		} else {
			return ResponseWrapper.success(200, "删除成功",null);
		}
	}
	
	@RequestMapping(value = "/{bussinessId}", method = RequestMethod.GET)
	@ApiOperation(value="根据业务信息查询审批历史", notes = "根据业务信息查询审批历史")
	/*@ApiImplicitParams({
		@ApiImplicitParam(name = "bussinessId", value = "业务id（业务类型+数据id组成，TEST:001）", paramType = "query")
	})*/
	public ResponseWrapper bussinessId(@PathVariable("bussinessId") String bussinessId){
		List<HistoryList> deploymentLists = flowTaskService.bussinessId(bussinessId);
		return ResponseWrapper.success(200, "查询成功", deploymentLists);
	}

	@RequestMapping(value = "completeTask", method = RequestMethod.POST)
	@ApiOperation(value="审批", notes = "审批（流程id与业务信息必传一个）")
	public  ResponseWrapper complete(
			@RequestBody FlowTodoVO completeVO
	) {
		int result= flowTaskService.completeTask(completeVO);
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if(result==0) {
			return ResponseWrapper.error(500,"该流程已结束",null);
		} else if(result==-1) {
			return ResponseWrapper.error(500,"您不能审批此节点",null);
		} else {
			modelMap.put("message", "审批成功");
			modelMap.put("data", completeVO.getProcessId());
			return ResponseWrapper.success(200, "启动成功", modelMap);
		}
	}
	
	
	
	@RequestMapping(value = "variableByBusiness", method = RequestMethod.GET)
	@ApiOperation(value="获取流程变量", notes = "获取流程变量")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "value", value = "变量 key键", paramType = "query"),
			@ApiImplicitParam(name = "bussinessId", value = "业务id（业务类型+数据id组成，TEST:001）", paramType = "query")

	})
	public  ResponseWrapper getVariableByBusiness(String value,String bussinessId) {
		Object result= flowTaskService.getVariableByBusiness(value,bussinessId);

			return ResponseWrapper.success(200, "获取成功", result);

	}
	
	
	
	@RequestMapping(value = "/taskInfo/{userId}/{bussinessId}", method = RequestMethod.POST)
	@ApiOperation(value="根据用户i", notes = "根据业务信息查询审批历史")
	public ResponseWrapper taskInfo(@PathVariable("userId") String userId,@PathVariable("bussinessId") String bussinessId){
		TaskStatus status = flowTaskService.taskInfo(userId,bussinessId);
		return ResponseWrapper.success(200, "查询成功", status);
	}
	
	@RequestMapping(value = "/taskInfos/{userId}/{bussinessId}", method = RequestMethod.POST)
	@ApiOperation(value="根据用户i", notes = "根据业务信息查询审批历史(多个逗号隔开)")
	public ResponseWrapper taskInfos(@PathVariable("userId") String userId,@PathVariable("bussinessId") String bussinessId){
		String[] bussinessIds = bussinessId.split(",");
		if(bussinessIds.length<=0) {
			return ResponseWrapper.success(200, "输入正确的业务id", null);
		}
		List<TaskStatus> task = new ArrayList<TaskStatus>();
		for(String bussiness:bussinessIds) {
			TaskStatus status = flowTaskService.taskInfo(userId,bussiness);
			task.add(status);
		}
		
		return ResponseWrapper.success(200, "查询成功", task);
	}
}
