package com.th.demo.controller.process;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.th.demo.model.system.Type;
import com.th.demo.tools.DateTools;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.rest.service.api.history.HistoricProcessInstanceCommentResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dell on 2018-11-15.
 */
@RestController
@RequestMapping(value = "/ProcessHistory")
public class HistoryController {
    @Autowired
    HistoryService historyService;
    @Autowired
    TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    String result = Type.FAIL;

    @RequestMapping(value = "/queryHistoryActInst.do")
    public String queryHistoryActInst(int page,
                                      int rows,
                                      String processInstanceId,
                                      String userId) throws IOException {

        PageHelper.startPage(page, rows);
        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceStartTime().orderByHistoricActivityInstanceEndTime().asc().list();

        List<Map<String, Object>> listmap = new ArrayList<>();
        Map<String, Object> map;
        for (int i = 0; i < list.size(); i++) {
            List<Comment> comments = taskService.getTaskComments(list.get(i).getTaskId());
            map = new HashMap<String, Object>();
            map.put("id", list.get(i).getId());
            map.put("name", list.get(i).getActivityName());
            // map.put("processInstanceId",list.get(i).getProcessInstanceId());
            map.put("startTime", DateTools.DateToStr(list.get(i).getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("endTime", DateTools.DateToStr(list.get(i).getEndTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("assignee", list.get(i).getAssignee());
            map.put("duration", DateTools.getDayHourMinSec(list.get(i).getDurationInMillis()));
            if (comments != null && comments.size()>0 ) {
                map.put("message", comments.get(0).getFullMessage());
            }else {
                map.put("message", "");
            }
            listmap.add(map);
        }
        // List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().listPage((page-1)*rows+1,page*rows);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(listmap);
        result = JSON.toJSONString(pageInfo);
        return result;
    }


    @RequestMapping(value = "/queryHistoryTaskInst.do")
    public String queryHistoryTaskInst(int page,
                                       int rows,
                                       String processInstanceId,
                                       String userId) throws IOException {

        PageHelper.startPage(page, rows);
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).taskDeleteReason("completed").orderByHistoricTaskInstanceStartTime().orderByHistoricTaskInstanceEndTime().asc().list();

        List<Map<String, Object>> listmap = new ArrayList<>();
        Map<String, Object> map;
        for (HistoricTaskInstance hti : list) {
            List<Comment> comments = taskService.getTaskComments(hti.getId());
            map = new HashMap<String, Object>();
            map.put("id", hti.getId());
            map.put("name", hti.getName());
            map.put("processInstanceId", hti.getProcessInstanceId());
            map.put("startTime", DateTools.DateToStr(hti.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("endTime", DateTools.DateToStr(hti.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("assignee", hti.getAssignee());
            if (comments != null && comments.size()>0 ) {
                map.put("message", comments.get(0).getFullMessage());
            }else {
                map.put("message", "");
            }
            listmap.add(map);
        }
        // List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().listPage((page-1)*rows+1,page*rows);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(listmap);
        result = JSON.toJSONString(pageInfo);
        return result;
    }


    @RequestMapping(value = "/queryHistoryProcInst.do")
    public String queryHistoryProcInst(int page,
                                       int rows,
                                       String userId) throws IOException {

        PageHelper.startPage(page, rows);
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().finished().orderByProcessInstanceStartTime().desc().list();

        List<Map<String, Object>> listmap = new ArrayList<>();
        Map<String, Object> map;
        for (int i = 0; i < list.size(); i++) {

            ProcessDefinition pi = repositoryService.createProcessDefinitionQuery().processDefinitionId(list.get(i).getProcessDefinitionId()).singleResult();

            if (pi != null) {
                map = new HashMap<String, Object>();
                map.put("id", list.get(i).getId());
                map.put("name", pi.getName());
                map.put("processInstanceId", list.get(i).getId());
                map.put("processDefinitionId", list.get(i).getProcessDefinitionId());
                map.put("startTime", DateTools.DateToStr(list.get(i).getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                map.put("endTime", DateTools.DateToStr(list.get(i).getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                map.put("duration", DateTools.getDayHourMinSec (list.get(i).getDurationInMillis()));
                map.put("startUserId", list.get(i).getStartUserId());
                listmap.add(map);
            }

        }
        // List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().listPage((page-1)*rows+1,page*rows);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(listmap);
        result = JSON.toJSONString(pageInfo);
        return result;
    }

}
