package com.bbd.bpm.controller.deployment;

import com.bbd.bpm.BpmResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * Created by houkang on 2019/2/22.
 */
@RestController
@RequestMapping("/bpm/model")
@Api(tags = {"流程管理"})
public class DeploymentController {
    private static final Logger Log = LoggerFactory.getLogger(DeploymentController.class);

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @ApiOperation(value = "查询流程列表")
    @GetMapping("/modelList")
    public BpmResponse modelList() {
        BpmResponse resp = new BpmResponse();
        try{
            List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery().list();
            resp.setData(processDefinitionList);
            resp.setSuccess(true);
            resp.setMessage("获取成功");
        }catch (Exception e){
            Log.error("获取失败",e);
            resp.setSuccess(false);
        }
      //todo
        return resp;
    }


    @ApiOperation(value = "删除流程")
    @GetMapping("/deleteModel")
    public BpmResponse deleteModel(String modelId) {
        BpmResponse resp = new BpmResponse();

       //todo
        try{
            repositoryService.deleteModel(modelId);
            System.out.println("删除流程成功，当前流程ID：" + modelId);
            resp.setSuccess(true);
            resp.setMessage("删除成功");
        }catch (Exception e){
            Log.error("删除失败",e);
            resp.setSuccess(false);
        }
        return resp;
    }



    @ApiOperation(value = "部署流程")
    @GetMapping("/deploymentModel")
    public BpmResponse deploymentModel(final String modelId) {
        BpmResponse resp = new BpmResponse();
        resp.setSuccess(true);
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            String processName = modelData.getName() + ".bpmn20.xml";
            DeploymentBuilder db = repositoryService.createDeployment().name(modelData.getName());
            Deployment deployment = db.addString(processName, new String(bpmnBytes,"utf-8")).deploy();
            //需要在 model表里保存 deploymentid
            modelData.setDeploymentId(deployment.getId());
            //保存 model
            //todo
            resp.setData(deployment.getId());
        } catch (Exception e) {
            Log.error(modelId+"部署失败",e);
            resp.setSuccess(false);
        }

        return resp;
    }

    @ApiOperation(value = "删除部署")
    @GetMapping("/deleteDeployment")
    public BpmResponse deleteDeployment(String deploymentId) {
        BpmResponse resp = new BpmResponse();
       // processEngine.getRepositoryService().deleteDeployment(deploymentId, true);
       //todo
        try{
            repositoryService.deleteDeployment(deploymentId, true);
            System.out.println("删除流程成功，当前流程部署ID：" + deploymentId);
            resp.setSuccess(true);
            resp.setMessage("删除成功");
        }catch (Exception e){
            Log.error("删除失败",e);
            resp.setSuccess(false);
        }
        return resp;
    }

    @ApiOperation(value = "开启流程")
    @GetMapping("/startModel")
    public BpmResponse startModel(final String deploymentId,String bussinessKey) {
        BpmResponse resp = new BpmResponse();
        resp.setSuccess(true);
        try {
            //获取流程定义
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).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);
            resp.setData(processId);
        } catch (Exception e) {
            Log.error(deploymentId+"开启失败",e);
            resp.setSuccess(false);
            resp.setMessage("开启失败");
        }

        return resp;


    }
}
