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.service.process.InstanceService;
import com.th.demo.service.system.SysUserService;
import com.th.demo.tools.DateTools;
import com.th.demo.tools.Tools;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
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.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by dell on 2018-11-13.
 */
@RestController
@RequestMapping(value = "/ProcessInstance")
public class InstanceController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private InstanceService instanceService;
    @Autowired
    private SysUserService sysUserService;

    String result = Type.FAIL;


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

        PageHelper.startPage(page, rows);
        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().list();

        List<Map<String,Object>> listmap = new ArrayList<>();
        Map<String,Object> map;
        for ( ProcessInstance pi :list) {
            HistoricProcessInstance hpi =  historyService.createHistoricProcessInstanceQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
            Task t = taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(t.getProcessDefinitionId()).singleResult();
            map= new HashMap<String,Object>();
            map.put("id", pi.getId());
            map.put("name", processDefinition.getName());
            map.put("processDefinitionId", pi.getProcessDefinitionId());
            map.put("processInstanceId", pi.getProcessInstanceId());
            map.put("assignee", t.getAssignee());
            map.put("isSuspended", pi.isSuspended());
            map.put("startTime", DateTools.DateToStr(hpi.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            if(hpi.getStartUserId()!=null) {
                String userName = sysUserService.queryByUserId(hpi.getStartUserId());
                map.put("startUserId", userName);
            }
            map.put("duration", DateTools.getDayHourMinSec (new Date(), hpi.getStartTime()));

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

    /**
     * 启动流程实例
     **/
    @RequestMapping(value = "/start.do")
    public String start(String key,
                        HttpServletRequest request) {
        try {
            String userId = (String)request.getAttribute("userId");
            instanceService.start(key,userId);
            result = Type.SUCCESS;
        } catch (Exception ex) {
            ex.printStackTrace();
            result = Type.FAIL + ex.getMessage();
        } finally {
            return result;
        }
    }


    /**
     * 删除 Instance
     */
    @RequestMapping(value = "/remove.do")
    public void delete(String instanceId,
                       String userId,
                       HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println(" instanceId=" + instanceId);
            runtimeService.deleteProcessInstance(instanceId, "test");

            System.out.println("删除成功，instanceId=" + instanceId);
            result = Type.SUCCESS;

        } catch (Exception ex) {
            ex.printStackTrace();
            result = Type.FAIL + ex.getMessage();
        } finally {
            Tools.out(response, result);
        }
    }


    /**
     * 暂停任务
     */
    @RequestMapping(value = "/suspend.do")
    public String suspend(String instanceId,
                          String userId,
                          HttpServletRequest request, HttpServletResponse response) {
        try {

            runtimeService.suspendProcessInstanceById(instanceId);
            result = Type.SUCCESS;

        } catch (Exception ex) {
            ex.printStackTrace();
            result = Type.FAIL + ex.getMessage();
        } finally {
            return result;
        }
    }

    /**
     * 激活
     */
    @RequestMapping(value = "/activate.do")
    public String activate(String instanceId,
                           String userId,
                           HttpServletRequest request, HttpServletResponse response) {
        try {
            runtimeService.activateProcessInstanceById(instanceId);
            result = Type.SUCCESS;
        } catch (Exception ex) {
            ex.printStackTrace();
            result = Type.FAIL + ex.getMessage();
        } finally {
            return result;
        }
    }
}
