package com.jeeplus.flowable.controller.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/commonApi")
public class CommonApi {

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

    /**
     * 根据procInsId获取当前流程节点名称
     * @param procInsId
     * @return
     */
    @GetMapping("/getTaskNameByProcInsId")
    public ResponseEntity<String> getTaskNameByProcInsId(@RequestParam("procInsId") String procInsId) {
        String res = getTaskName(procInsId);
        return ResponseEntity.ok(res);
    }

    /**
     * 判断当前审核节点是否为最后一个节点
     * @param procInsId
     * @return
     */
    @GetMapping("/isLastTask")
    @Deprecated
    public ResponseEntity<Boolean> isLastTask(@RequestParam("procInsId") String procInsId) {
        Task task = taskService.createTaskQuery().processInstanceId(procInsId).active().singleResult();
        // task为null则审核节点为最后一个审核节点
        if (ObjectUtil.isEmpty(task)) {
            return ResponseEntity.ok(true);
        }
        return ResponseEntity.ok(false);
    }

    /**
     * 根据procInsId获取当前流程节点名称
     * @param procInsId
     * @return
     */
    public String getTaskName(String procInsId) {
        if (StringUtils.isNotBlank(procInsId)) {
            Task task = taskService.createTaskQuery().processInstanceId(procInsId).active().singleResult();
            if (task!=null) {
                //获取流程发布Id信息
                String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).singleResult().getProcessDefinitionId();
                //获取bpm对象
                BpmnModel bpmnModel = SpringUtil.getBean (RepositoryService.class).getBpmnModel(definitionId);
                //传节点定义key 获取当前节点
                FlowNode flowNode = (FlowNode) bpmnModel.getFlowElement(task.getTaskDefinitionKey());
                if (ObjectUtil.isNotEmpty(flowNode)) {
                    if (StringUtils.isNotBlank(flowNode.getName())) {
                        return flowNode.getName();
                    }
                }
            }
        }
        return "";
    }
}
