/**
   * Get the average time duration of completed processes
   *
   * @return list with the completed processes and the average time duration taken for each process
   */
  @GET
  @Path("/avgDurationToCompleteProcess/")
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public ResponseHolder getAvgTimeDurationForCompletedProcesses() {
    List<ProcessDefinition> deployements =
        BPMNOSGIService.getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionTenantId(str)
            .list();

    ResponseHolder response = new ResponseHolder();
    List list = new ArrayList<>();

    for (ProcessDefinition instance : deployements) {
      CompletedProcesses bpmnProcessInstance = new CompletedProcesses();
      bpmnProcessInstance.setProcessDefinitionId(instance.getId());

      double totalTime = 0;
      double averageTime = 0;
      String processDefinitionID = instance.getId();

      HistoricProcessInstanceQuery historicProcessInstanceQuery =
          BPMNOSGIService.getHistoryService()
              .createHistoricProcessInstanceQuery()
              .processInstanceTenantId(str)
              .processDefinitionId(processDefinitionID)
              .finished();

      long noOfHistoricInstances = historicProcessInstanceQuery.count();

      if (noOfHistoricInstances == 0) {
      } else {
        List<HistoricProcessInstance> instanceList = historicProcessInstanceQuery.list();

        for (HistoricProcessInstance completedProcess : instanceList) {
          double timeDurationOfTask = completedProcess.getDurationInMillis();
          double timeInMins = timeDurationOfTask / (1000 * 60);
          totalTime += timeInMins;
        }
        averageTime = totalTime / noOfHistoricInstances;
        bpmnProcessInstance.setAverageTimeForCompletion(averageTime);
        list.add(bpmnProcessInstance);
      }
    }
    response.setData(list);
    return response;
  }
  /**
   * Average task duration for completed processes
   *
   * @param pId processDefintionId of the process selected to view the average time duration for
   *     each task
   * @return list of completed tasks with the average time duration for the selected process
   */
  @GET
  @Path("/avgTaskDurationForCompletedProcess/{pId}")
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public ResponseHolder avgTaskTimeDurationForCompletedProcesses(@PathParam("pId") String pId) {
    long countOfProcesses =
        BPMNOSGIService.getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionTenantId(str)
            .processDefinitionId(pId)
            .count();
    if (countOfProcesses == 0) {
      throw new ActivitiObjectNotFoundException(
          "Could not find process with process definition id '" + pId + "'.");
    }

    ResponseHolder response = new ResponseHolder();
    List taskListForProcess = new ArrayList<>();
    HashMap<String, Long> map = new HashMap<String, Long>();
    // Get the number of completed/finished process instance for each process definition
    HistoricProcessInstanceQuery historicProcessInstanceQuery =
        BPMNOSGIService.getHistoryService()
            .createHistoricProcessInstanceQuery()
            .processInstanceTenantId(str)
            .processDefinitionId(pId)
            .finished();
    // Get the count of the complete process instances
    long noOfHistoricInstances = historicProcessInstanceQuery.count();

    // If the deployed process doesnot have any completed process instances --> Ignore
    if (noOfHistoricInstances == 0) {
      response.setData(taskListForProcess);
    }
    // If the deployed process has completed process instances --> then
    else {

      BPMNTaskInstance tInstance = new BPMNTaskInstance();
      // Get the list of completed tasks/activities in the completed process instance by passing the
      // process definition id of the process
      List<HistoricTaskInstance> taskList =
          BPMNOSGIService.getHistoryService()
              .createHistoricTaskInstanceQuery()
              .taskTenantId(str)
              .processDefinitionId(pId)
              .processFinished()
              .list();
      // Iterate through each completed task/activity and get the task name and duration
      for (HistoricTaskInstance taskInstance : taskList) {
        // Get the task name
        String taskKey = taskInstance.getTaskDefinitionKey();
        // Get the time duration taken for the task to be completed
        long taskDuration = taskInstance.getDurationInMillis();

        if (map.containsKey(taskKey)) {
          long tt = map.get(taskKey);
          map.put(taskKey, taskDuration + tt);
        } else {
          map.put(taskKey, taskDuration);
        }
        // Iterating Task List finished
      }
      Iterator iterator = map.keySet().iterator();
      while (iterator.hasNext()) {
        String key = iterator.next().toString();
        double value = map.get(key) / noOfHistoricInstances;
        tInstance = new BPMNTaskInstance();
        tInstance.setTaskDefinitionKey(key);
        tInstance.setAverageTimeForCompletion(value);
        taskListForProcess.add(tInstance);
      }

      response.setData(taskListForProcess);
    }
    return response;
  }
  /**
   * @Title: myWorkTaskData @Description: TODO
   *
   * @param request
   * @param response
   * @param dataGrid void
   * @throws
   * @exception
   * @author fly
   * @date 2015年6月23日 上午10:20:42
   */
  @RequestMapping(params = "myWorkTaskData")
  public void myWorkTaskData(
      HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

    String userId = ResourceUtil.getSessionUserName().getId();
    // involvedUser 当前用户相关的
    HistoricProcessInstanceQuery query =
        historyService.createHistoricProcessInstanceQuery().involvedUser(userId);

    List<HistoricProcessInstance> historicTasks =
        query
            .orderByProcessInstanceStartTime()
            .desc()
            .listPage(dataGrid.getStart(), dataGrid.getEnd());
    long total = query.count();
    System.out.println(dataGrid.getStart() + " end: " + dataGrid.getEnd());
    StringBuffer rows = new StringBuffer();
    for (HistoricProcessInstance t : historicTasks) {
      ProcessDefinition processDefinition =
          repositoryService.getProcessDefinition(t.getProcessDefinitionId());

      rows.append(
          "{'id':'"
              + t.getId()
              + "','key':'"
              + processDefinition.getName()
              + "-"
              + DateUtils.date_sdf.format(t.getStartTime())
              + "','taskId':'"
              + t.getId()
              + "'");
      // 流程详细查看
      WorkFlowSetEntity workFlowSet =
          systemService.findUniqueByProperty(
              WorkFlowSetEntity.class, "deploymentId", processDefinition.getDeploymentId());
      if (workFlowSet != null) {
        rows.append(",'action':'" + workFlowSet.getDetailUrl() + "'");
      }
      // 流程用户处理
      if (t.getStartUserId() != null) {
        TSUser user = systemService.get(TSUser.class, t.getStartUserId());
        rows.append(",'username':'******'");
      }

      // 流程开始结束时间处理
      if (t.getStartTime() == null) {
        rows.append(",'beginDate':'无'");
      } else {
        rows.append(",'beginDate':'" + DateUtils.datetimeFormat.format(t.getStartTime()) + "'");
      }
      if (t.getEndTime() == null) {
        rows.append(",'endDate':'无','stateType':'办理中'");

      } else {
        rows.append(
            ",'endDate':'"
                + DateUtils.datetimeFormat.format(t.getEndTime())
                + "','stateType':'已完成'");
      }
      rows.append("},");
    }
    String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

    JSONObject jObject = JSONObject.fromObject("{'total':" + total + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }