package com.bbd.bpm.controller;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * Created by houkang on 2019/1/28.
 */
@RestController
@RequestMapping("/bpm/task")
public class ProcessTaskController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    //启动工作流  并执行到下一节点
    @GetMapping("/beginTask")
    public void beginTask(String bussinessKey,String job) {

        //根据bpmn文件部署流程
        Deployment deployment = repositoryService.createDeployment().addClasspathResource("processes/bpm_two.bpmn").deploy();
        //获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
        //启动流程定义，返回流程实例
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("user","yuagong1");
        ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinition.getKey(), bussinessKey,variables);
        String processId = pi.getId();
        System.out.println("流程创建成功，当前流程实例ID：" + processId);

        //完成并执行到下一节点
        Task task = taskService.createTaskQuery().processInstanceId(processId).singleResult();
        System.out.println("第一次执行前，任务名称：" + task.getName());
        Map<String, Object> assMap = new HashMap<String, Object>();
        assMap.put("job",job);
        taskService.complete(task.getId(),assMap);

        System.out.println("执行结束");
    }


    //完成工作
    @GetMapping("/processTask")
    public void processTask(String taskId) {
        Task task =  taskService.createTaskQuery().taskId(taskId).singleResult();
        if(task==null){
            System.out.println("任务不存在");
            return;
        }

        // 由于流程用户上下文对象是线程独立的，所以要在需要的位置设置，要保证设置和获取操作在同一个线程中
        Authentication.setAuthenticatedUserId("lingdao");//批注人的名称  一定要写，不然查看的时候不知道人物信息
        // 添加批注信息
        taskService.addComment(taskId, null, "");//comment为批注内容
        Map<String, Object> variables = new HashMap<String, Object>();
        taskService.complete(taskId,variables);
    }

}
