package com.blueland.bpm.manage.web;

import com.blueland.bpm.application.model.ApplicationEntity;
import com.blueland.bpm.application.service.ApplicationManager;
import com.blueland.bpm.common.base.BaseSpringController;
import com.blueland.bpm.common.page.Page;
import com.blueland.bpm.engine.config.model.ActivityInfoConfig;
import com.blueland.bpm.engine.config.service.ActivityInfoConfigManager;
import com.blueland.bpm.engine.core.model.SearchProcessListDTO;
import com.blueland.bpm.engine.core.service.ProcessInstanceService;
import com.blueland.bpm.manage.countAnalysis.service.AnalysisService;
import com.blueland.bpm.manage.util.BaseUser;
import com.blueland.bpm.manage.util.MyContants;
import com.blueland.unitework.service.UniteworkService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 作者: 李立灿
 * 日期: 2018年10月22日
 * 时间: 2018年10月22日
 */

@Controller
@RequestMapping(value = "sysMgr")
public class sysMgrController extends BaseSpringController{
	@Autowired
	private ProcessInstanceService processInstanceService;
	@Autowired
	private ApplicationManager applicationManager;
	@Autowired
	private ActivityInfoConfigManager activityInfoConfigManager;
	@Autowired
	private AnalysisService analysisService;
	@Autowired
	private UniteworkService uniteworkService;
	
	/** 
	 * 流程运行统计 查询
	 **/
	@RequestMapping(value = "appProcessList")
	public ModelAndView appProcessList(HttpServletRequest request) throws Exception{
		String startDate = "";
		String endDate = "";
		String searchYear = "";
		if(StringUtils.isNotEmpty(request.getParameter("searchMouth"))){
			System.out.println(getMonthEndTime(Integer.parseInt(request.getParameter("searchMouth"))));
		}
		if(StringUtils.isNotEmpty(request.getParameter("toSearchYear"))){
			if(StringUtils.isNotEmpty(request.getParameter("searchYear"))){
				searchYear = request.getParameter("searchYear");
				if(StringUtils.isNotEmpty(request.getParameter("searchMouth"))){
					int dayNum = getMonthEndTime(Integer.parseInt(request.getParameter("searchMouth")));
					startDate = searchYear + "-"+request.getParameter("searchMouth").toString()+"-01";
					endDate = searchYear + "-"+request.getParameter("searchMouth").toString()+"-"+dayNum;
				}else{
					startDate = searchYear + "-01-01";
					endDate = (Integer.parseInt(searchYear) + 1) + "-01-01";
				}
			}
		}else{
			Date nowDate = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy");
			searchYear = format.format(nowDate);
			if(StringUtils.isNotEmpty(request.getParameter("searchMouth"))){
				int dayNum = getMonthEndTime(Integer.parseInt(request.getParameter("searchMouth")));
				startDate = searchYear + "-"+request.getParameter("searchMouth").toString()+"-01";
				endDate = searchYear + "-"+request.getParameter("searchMouth").toString()+"-"+dayNum;
			}else{
				startDate = searchYear + "-01-01";
				endDate = (Integer.parseInt(searchYear) + 1) + "-01-01";
			}
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("appId", request.getParameter("appId"));
		params.put("searchYear", searchYear);
		params.put("searchMouth", request.getParameter("searchMouth"));
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		List<Map<String , Object>> resultMap = analysisService.getAppProcessRunIndex(params);
		
		int appSum = 0;
		int runtaskSum = 0;
		int procinstOneSum = 0;
		int procinstFiveSum = 0;
		int procdefSum = 0;
		for (Map<String, Object> map : resultMap) {
			appSum += 1;
			if(map.get("RUNTASKNUM") != null && map.get("RUNTASKNUM") != ""){
				runtaskSum += Integer.parseInt(map.get("RUNTASKNUM").toString());
			}
			if(map.get("PROCINSTONENUM") != null && map.get("PROCINSTONENUM") != ""){
				procinstOneSum += Integer.parseInt(map.get("PROCINSTONENUM").toString());
			}
			if(map.get("PROCINSTFIVENUM") != null && map.get("PROCINSTFIVENUM") != ""){
				procinstFiveSum += Integer.parseInt(map.get("PROCINSTFIVENUM").toString());
			}
			if(map.get("PROCDEFNUM") != null && map.get("PROCDEFNUM") != ""){
				procdefSum += Integer.parseInt(map.get("PROCDEFNUM").toString());
			}
		}
		params.put("appSum", appSum);
		params.put("runtaskSum", runtaskSum);
		params.put("procinstOneSum", procinstOneSum);
		params.put("procinstFiveSum", procinstFiveSum);
		params.put("procdefSum", procdefSum);
		ApplicationEntity appModel = new ApplicationEntity();
		appModel.setAppType("inner");
		List<ApplicationEntity> applicationList =  applicationManager.findByExample(appModel);
		
		ModelAndView result = new ModelAndView("/sysMgr/appProcessList");
		result.addObject("params", params);
		result.addObject("resultMap", resultMap);
		result.addObject("applicationList", applicationList);
		return result;
	}
	
	/** 
	 * 流程实例查询
	 **/
	@RequestMapping(value="/sysProcessInstList")
	public ModelAndView sysProcessInstlist(SearchProcessListDTO pageRequest,HttpServletRequest request) throws Exception {
		HistoricProcessInstanceQuery query=processInstanceService.getHistoryService().createHistoricProcessInstanceQuery();
		pageRequest = (SearchProcessListDTO) bindPageRequest(request,pageRequest, "");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("appId", request.getParameter("appId"));
		params.put("title", request.getParameter("title"));
		params.put("processInstanceId", request.getParameter("processInstanceId"));
		params.put("userId", request.getParameter("userId"));
		params.put("procState", request.getParameter("procState"));
		params.put("searchYear", request.getParameter("searchYear"));
		params.put("toSearchYear", request.getParameter("toSearchYear"));
		params.put("searchMouth", request.getParameter("searchMouth"));
		params.put("toProcState", request.getParameter("toProcState"));
		params.put("processDefName", request.getParameter("processDefName"));
		String toSearchYear = "";
		if(StringUtils.isNotEmpty(request.getParameter("toSearchYear"))){
			toSearchYear = request.getParameter("toSearchYear");
		}else if(StringUtils.isNotEmpty(request.getParameter("searchYear"))){
			toSearchYear = request.getParameter("searchYear");
		}
		if (StringUtils.isNotEmpty(pageRequest.getProcessDefName())) {
			query.processDefinitionName(request.getParameter("processDefName"));
			
		}
		if (StringUtils.isNotEmpty(request.getParameter("toProcState"))) {
			query.procState(Integer.parseInt(request.getParameter("toProcState")));
		}
		if (StringUtils.isNotEmpty(request.getParameter("appId"))) {
			query.processInstanceTenantId(request.getParameter("appId"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("title"))) {
			query.procTitle(request.getParameter("title"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("processInstanceId"))) {
			query.processInstanceId(request.getParameter("processInstanceId"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("procState"))) {
			query.procState(Integer.parseInt(request.getParameter("procState")));
		}
		if (StringUtils.isNotEmpty(request.getParameter("userId"))) {
			query.startedBy(request.getParameter("userId"));
		}
		if (StringUtils.isNotEmpty(toSearchYear)) {
			if(StringUtils.isNotEmpty(request.getParameter("searchMouth"))){
				int dayNum = getMonthEndTime(Integer.parseInt(request.getParameter("searchMouth")));
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				String searchYear = toSearchYear + "-" + request.getParameter("searchMouth").toString()+"-01";
				String endDateStr = toSearchYear + "-" + request.getParameter("searchMouth").toString()+"-"+dayNum;
				Date startDate = format.parse(searchYear);
				Date endDate = format.parse(endDateStr);
				query.startedAfter(startDate);
				query.startedBefore(endDate);
			}else{
				if(StringUtils.isEmpty(request.getParameter("flag"))){
					SimpleDateFormat format = new SimpleDateFormat("yyyy");
					String searchYear = toSearchYear;
					String endDateStr = (Integer.parseInt(searchYear) + 1) + "";
					Date startDate = format.parse(searchYear);
					Date endDate = format.parse(endDateStr);
					query.startedAfter(startDate);
					query.startedBefore(endDate);
				}
			}
		}else{
			if(StringUtils.isEmpty(request.getParameter("flag"))){
				Date nowDate = new Date();
				SimpleDateFormat format = new SimpleDateFormat("yyyy");
				String searchYear = format.format(nowDate);
				String endDateStr = (Integer.parseInt(searchYear) + 1) + "";
				Date startDate = format.parse(searchYear);
				Date endDate = format.parse(endDateStr);
				query.startedAfter(startDate);
				query.startedBefore(endDate);
				params.put("searchYear", searchYear);
				params.put("searchMouth", "");
			}
			
		}

		Page page = new Page(pageRequest, (int) query.count());
		List<HistoricProcessInstance> historicProcessInstances=query.orderByProcessInstanceStartTime().desc().listPage(page.getFirstResult(),page.getPageSize());
		page.setResult(historicProcessInstances);

		ApplicationEntity appModel = new ApplicationEntity();
		appModel.setAppType("inner");
		List<ApplicationEntity> applicationList =  applicationManager.findByExample(appModel);
		ModelAndView modelAndView = new ModelAndView("/sysMgr/sysProcessInstList");
		modelAndView.addObject("params", params);
		modelAndView.addObject("applicationList", applicationList);
		modelAndView.addObject("isBpmAdmin",BaseUser.isEbpmAdmin(BaseUser.getInstance().getSessionUser(request)));
		modelAndView.addAllObjects(toModelMap(page, pageRequest));
		return modelAndView;
	}
	
	/** 
	 * 流程待办查询
	 **/
	@RequestMapping(value = "/sysTaskList")
	public ModelAndView sysTaskList(SearchProcessListDTO pageRequest, HttpServletRequest request) throws Exception {
		TaskQuery query = processInstanceService.getTaskService().createTaskQuery();
		pageRequest = (SearchProcessListDTO) bindPageRequest(request,pageRequest, "");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("appId", request.getParameter("appId"));
		params.put("title", request.getParameter("title"));
		params.put("processInstanceId", request.getParameter("processInstanceId"));
		params.put("processDefName", request.getParameter("processDefName"));
		params.put("assignee", request.getParameter("assignee"));
		params.put("actInstId", request.getParameter("actInstId"));
		params.put("actInstName", request.getParameter("actInstName"));
		params.put("toSearchYear", request.getParameter("toSearchYear"));
		params.put("taskDefName", request.getParameter("taskDefName"));
		if (StringUtils.isNotEmpty(request.getParameter("taskDefName"))) {
			query.preTaskDefName(request.getParameter("taskDefName"));
		}
		if ("true".equalsIgnoreCase(MyContants.IS_OPEN_TENANT) && (StringUtils.isNotEmpty(request.getParameter("appId")))) {
			query.taskTenantId(request.getParameter("appId"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("title"))) {
			query.procTitle(request.getParameter("title"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("processInstanceId"))) {
			query.processInstanceId(request.getParameter("processInstanceId"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("processDefName"))) {
			query.processDefinitionNameLike("%"+request.getParameter("processDefName")+"%");
		}
		if (StringUtils.isNotEmpty(request.getParameter("assignee"))) {
			query.taskAssignee(request.getParameter("assignee"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("actInstId"))) {
			query.taskId(request.getParameter("actInstId"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("actInstName"))) {
			query.taskName(request.getParameter("actInstName"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("toSearchYear"))) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy");
			String searchYear = request.getParameter("toSearchYear");
			String endDateStr = (Integer.parseInt(searchYear) + 1) + "";
			Date startDate = format.parse(searchYear);
			Date endDate = format.parse(endDateStr);
			query.taskCreatedAfter(startDate);
			query.taskCreatedBefore(endDate);
		}
		Page<Task> page = new Page<Task>(pageRequest, (int) query.count());
		List<Task> tasks = query.orderByTaskCreateTime().desc().listPage(page.getFirstResult(), page.getPageSize());
		page.setResult(tasks);

		ApplicationEntity appModel = new ApplicationEntity();
		appModel.setAppType("inner");
		List<ApplicationEntity> applicationList =  applicationManager.findByExample(appModel);
		ModelAndView modelAndView = new ModelAndView("/sysMgr/sysTaskList");
		modelAndView.addObject("params", params);
		modelAndView.addObject("applicationList", applicationList);
		modelAndView.addAllObjects(toModelMap(page, pageRequest));
		return modelAndView;
	}
	

	/** 
	 * 流程接口调用时序
	 **/
	@RequestMapping(value = "/appProcessLogByYear")
	public ModelAndView appProcessLogByYear(HttpServletRequest request) throws Exception {
//		String column = "{name: '个人印章使用申请',data: eval([0,0,0,0,0,0,0,0,0,4,0,0])},{name: '临时出入证申请',data: eval([0,0,0,0,0,0,0,0,0,9,0,0])},{name: '公务印章使用申请',data: eval([0,0,0,0,0,0,0,0,0,1,0,0])},{name: '收入证明申请',data: eval([0,0,0,0,0,0,0,0,0,2,0,0])},{name: '综合协调事项',data: eval([0,0,0,0,0,0,0,0,0,6,0,0])},{name: '请假',data: eval([0,0,0,0,0,0,0,0,0,2,0,0])},{name: '车辆出入证申请',data: eval([0,0,0,0,0,0,0,0,0,5,0,0])},";
		String column = "";
		String row = "";
		int total = 0;
		//获取横坐标数据
		List<String> monthList = initMonth();
		for (String month : monthList) {
			row += "'" + month + "月',";
		}
		if (!StringUtils.isEmpty(row)) {
			row = row.substring(0, row.length() - 1);
		}
		//获取流程接口调用时序总数
		String searchYear = "";
		if(StringUtils.isNotEmpty(request.getParameter("searchYear"))){
			searchYear = request.getParameter("searchYear");
		}else{
			Date nowDate = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy");
			searchYear = format.format(nowDate);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("searchYear", searchYear);
		params.put("appId", request.getParameter("appId"));
		List<Map<String , Object>> processLogResult = analysisService.getAppProcessLogByYear(params);
		
		Map<String, List> resultMap = new LinkedHashMap<String, List>();
		for (Map<String , Object> result : processLogResult) {
			if (resultMap.containsKey(result.get("APPNAME"))) {
				List resultList = (List) resultMap.get(result.get("APPNAME"));
				resultList.add(result);
			} else {
				List resultList = new ArrayList();
				resultList.add(result);
				resultMap.put(result.get("APPNAME").toString(), resultList);
			}
			int runCountInt = Integer.parseInt(result.get("RUNCOUNT").toString());
			if (!StringUtils.isEmpty(result.get("RUNCOUNT").toString())) {
				total += runCountInt;
			}
		}
		//获取纵坐标数据
		for (Map.Entry<String, List> entry : resultMap.entrySet()) {
			List<Map<String, List>> processLogResultList = entry.getValue();
			String data = "";
			column += "{name: '" + entry.getKey() + "',";
			for (String month : monthList) {
				boolean isContains = false;
				Map<String, List> processLog = null;
				for (Map<String, List> processLog1 : processLogResultList) {
					if (month.equals(processLog1.get("MONTH"))) {
						isContains = true;
						processLog = processLog1;
						break;
					}
				}
				if (isContains) {
					data += processLog.get("RUNCOUNT") + ",";
				} else {
					data += "0,";
				}
			}
			if (!StringUtils.isEmpty(data)) {
				data = data.substring(0, data.length() - 1);
			}
			column += "data: eval([" + data + "])},";
		}

		ApplicationEntity appModel = new ApplicationEntity();
		appModel.setAppType("inner");
		List<ApplicationEntity> applicationList =  applicationManager.findByExample(appModel);
		ModelAndView modelAndView = new ModelAndView("/sysMgr/appProcessLogByYear");
		modelAndView.addObject("applicationList", applicationList);
		modelAndView.addObject("params", params);
		modelAndView.addObject("column", column);
		modelAndView.addObject("row", row);
		modelAndView.addObject("total", total);
		return modelAndView;
	}
	
	/** 
	 * 流程接口调用时序
	 **/
	@RequestMapping(value = "/appProcessLogByDay")
	public ModelAndView appProcessLogByDay(HttpServletRequest request) throws Exception {
//		String column = "{name: '运行中(20)',data: eval([6,5,3,2,2,1,1])},{name: '已结束(9)',data: eval([3,2,2,1,1])},";
//		String row = "'临时出入证申请','综合协调事项','临时出入证申请','车辆出入证申请','请假','个人印章使用申请','个人印章使用申请','车辆出入证申请','综合协调事项','公务印章使用申请','收入证明申请','收入证明申请'";
		String column = "";
		String row = "";
		int total = 0;
		//获取流程接口调用时序数据
		String searchDay = "";
		if(StringUtils.isNotEmpty(request.getParameter("searchDay"))){
			searchDay = request.getParameter("searchDay");
		}else{
			Date nowDate = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			searchDay = format.format(nowDate);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("searchDay", searchDay);
		params.put("appId", request.getParameter("appId"));
		List<Map<String , Object>> processLogResult = analysisService.getAppProcessLogByDay(params);

		ApplicationEntity appModel = new ApplicationEntity();
		appModel.setAppType("inner");
		List<ApplicationEntity> applicationList =  applicationManager.findByExample(appModel);
		String data = "";
		for (Map<String, Object> processLog : processLogResult) {
			//获取横坐标数据
			row += "'" + processLog.get("APPNAME") + "',";
			//获取totle
			int runCountInt = Integer.parseInt(processLog.get("RUNCOUNT").toString());
			if (StringUtils.isNotEmpty(processLog.get("RUNCOUNT").toString())) {
				total += runCountInt;
			}
			data += processLog.get("RUNCOUNT") + ",";
		}
		if (!StringUtils.isEmpty(row)) {
			row = row.substring(0, row.length() - 1);
		}
		//获取纵坐标数据
		column += "{name: '今日各流程调用数',";
		if (!StringUtils.isEmpty(data)) {
			data = data.substring(0, data.length() - 1);
		}
		column += "data: eval([" + data + "])},";
//		for (Map<String, Object> processLog : processLogResult) {
//			data += processLog.get("RUNCOUNT") + ",";
//		}
//		for (ApplicationEntity model : applicationList) {
//			row += "'" + model.getAppName() + "',";
//		}
		//获取totle
//		for (Map<String, Object> processLog1 : processLogResult) {
//			int runCountInt = Integer.parseInt(processLog1.get("RUNCOUNT").toString());
//			if (StringUtils.isNotEmpty(processLog1.get("RUNCOUNT").toString())) {
//				total += runCountInt;
//			}
//		}
//		for (ApplicationEntity model : applicationList) {
//			boolean isContains = false;
//			Map<String, Object> processLog = null;
//			for (Map<String, Object> processLog1 : processLogResult) {
//				if (model.getAppName().equals(processLog1.get("APPNAME"))) {
//					isContains = true;
//					processLog = processLog1;
//					break;
//				}
//			}
//			if (isContains) {
//				data += processLog.get("RUNCOUNT") + ",";
//			} else {
//				data += "0,";
//			}
//		}
			
		ModelAndView modelAndView = new ModelAndView("/sysMgr/appProcessLogByDay");
		modelAndView.addObject("applicationList", applicationList);
		modelAndView.addObject("params", params);
		modelAndView.addObject("column", column);
		modelAndView.addObject("row", row);
		modelAndView.addObject("total", total);
		return modelAndView;
	}
	
	@RequestMapping(value="/getAppName", method = RequestMethod.GET)
	public @ResponseBody String getAppName(HttpServletRequest request) {
		ApplicationEntity appModel = new ApplicationEntity();
		appModel.setAppType("inner");
		List<ApplicationEntity> applicationList =  applicationManager.findByExample(appModel);
		String appName = "";
		for (ApplicationEntity entity : applicationList) {
			if(request.getParameter("appId").equals(entity.getAppId())){
				appName = entity.getAppName();
			}
		}
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        String s = gson.toJson(appName);
		return s;
	}
	/** 
	 * 流程已办查询
	 **/
	@RequestMapping(value = "/sysYibanTaskList")
	public ModelAndView sysYibanTaskList(SearchProcessListDTO pageRequest, HttpServletRequest request) throws Exception {
		HistoricTaskInstanceQuery query = processInstanceService.getHistoryService().createHistoricTaskInstanceQuery();
		pageRequest = (SearchProcessListDTO) bindPageRequest(request,pageRequest, "");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("appId", request.getParameter("appId"));;
		params.put("title", request.getParameter("title"));
		params.put("processInstanceId", request.getParameter("processInstanceId"));
		params.put("processDefName", request.getParameter("processDefName"));
		params.put("assignee", request.getParameter("assignee"));
		params.put("actInstId", request.getParameter("actInstId"));
		params.put("actInstName", request.getParameter("actInstName"));
		params.put("toSearchYear", request.getParameter("toSearchYear"));
		params.put("taskDefName", request.getParameter("taskDefName"));
		if ("true".equalsIgnoreCase(MyContants.IS_OPEN_TENANT) && (StringUtils.isNotEmpty(request.getParameter("appId")))) {
			query.taskTenantId(request.getParameter("appId"));
		}
		/*if (StringUtils.isNotEmpty(request.getParameter("title"))) {
			query.taskNameLike("%"+request.getParameter("title")+"%");
		}*/
		if (StringUtils.isNotEmpty(request.getParameter("processInstanceId"))) {
			query.processInstanceId(request.getParameter("processInstanceId"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("processDefName"))) {
			query.processDefinitionNameLike("%"+request.getParameter("processDefName")+"%");
		}
		if (StringUtils.isNotEmpty(request.getParameter("assignee"))) {
			query.taskAssignee(request.getParameter("assignee"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("actInstId"))) {
			query.taskId(request.getParameter("actInstId"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("actInstName"))) {
			query.taskName(request.getParameter("actInstName"));
		}
		if (StringUtils.isNotEmpty(request.getParameter("toSearchYear"))) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy");
			String searchYear = request.getParameter("toSearchYear");
			String endDateStr = (Integer.parseInt(searchYear) + 1) + "";
			Date startDate = format.parse(searchYear);
			Date endDate = format.parse(endDateStr);
			query.taskCreatedAfter(startDate);
			query.taskCreatedBefore(endDate);
		}
		Page<HistoricTaskInstance> page = new Page<HistoricTaskInstance>(pageRequest, (int) query.count());
		List<HistoricTaskInstance> tasks = query.orderByTaskCreateTime().desc().listPage(page.getFirstResult(), page.getPageSize());
		for (HistoricTaskInstance task : tasks) {
			try {
				HistoricTaskInstanceEntity taskEntity = (HistoricTaskInstanceEntity) task;
				String desc = "";
				ActivityInfoConfig activityInfoConfig = activityInfoConfigManager.getActivityInfoConfig(taskEntity.getProcessDefinitionId(), taskEntity.getTaskDefinitionKey());
				if (activityInfoConfig.getActivityLimitTime() != null && activityInfoConfig.getActivityLimitTime() != 0) {
					Date dueDate = DateUtils.addDays(taskEntity.getCreateTime(), activityInfoConfig.getActivityLimitTime());
					long limitDate = differByDay(dueDate, new Date());
					if (limitDate > 0) {
						desc = "超时" + limitDate + "天";
					} else {
						desc = "剩余" + Math.abs(limitDate) + "天";
					}
				} else {
					desc = "耗时" + differByDay(taskEntity.getCreateTime(), new Date()) + "天";
				}
				taskEntity.setDescription(desc);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		page.setResult(tasks);

		ApplicationEntity appModel = new ApplicationEntity();
		appModel.setAppType("inner");
		List<ApplicationEntity> applicationList =  applicationManager.findByExample(appModel);
		ModelAndView modelAndView = new ModelAndView("/sysMgr/sysYibanTaskList");
		modelAndView.addObject("params", params);
		modelAndView.addObject("applicationList", applicationList);
		modelAndView.addAllObjects(toModelMap(page, pageRequest));
		return modelAndView;
	}
	public static long differByDay(Date startDate, Date endDate) {
		if (startDate == null || endDate == null) {
			return 0;
		}
		return (endDate.getTime() / 86400000 - startDate.getTime() / 86400000);
	}	
	private List initMonth(){
		List months=new ArrayList();
		for (int i = 1; i <=12; i++) {
			if(i<10){
				months.add("0"+i);
			}else{
				months.add(""+i);
			}
		}
		return months;
	}
	
	//获得最后一天，传入的参数是一个int类型的年份与月份
    private int getMonthEndTime(int month) throws Exception {
        //选中月份的最后一天
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, month - 1);
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        return lastDay;
    }
}
