package com.izouma.awesomeadmin.web.activiti;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.izouma.awesomeadmin.dto.Result;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.*;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/activiti/model")
@RequiresAuthentication
@RequiresRoles("admin")
public class ModelController {
    @Autowired
    private IdentityService                identityService;
    @Autowired
    private RepositoryService              repositoryService;
    @Autowired
    private RuntimeService                 runtimeService;
    @Autowired
    private TaskService                    taskService;
    @Autowired
    private ManagementService              managementService;
    @Autowired
    private FormService                    formService;
    @Autowired
    private ProcessEngineConfigurationImpl processEngineConfiguration;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Result processList(String name) {
        ModelQuery query = repositoryService.createModelQuery();
        if (StringUtils.isNotEmpty(name)) {
            query = query.modelNameLike(name);
        }
        List<Model> models = query.list();
        return new Result(true, models);
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    @ResponseBody
    public Result createModel(String name, String description) {
        Model newModel = repositoryService.newModel();
        try {

            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            newModel.setMetaInfo(modelObjectNode.toString());
            newModel.setName(name);
            repositoryService.saveModel(newModel);
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.set("stencilset", stencilSetNode);
            repositoryService.addModelEditorSource(newModel.getId(),
                    editorNode.toString().getBytes("utf-8"));
            return new Result(true, newModel.getId());
        } catch (Exception e) {
            e.getStackTrace();
        }
        return new Result(false, "创建失败");
    }

    @RequestMapping(value = "/publish", method = RequestMethod.GET)
    @ResponseBody
    public Result publishModel(@RequestParam("id") String id) {
        try {
            Model modelData = repositoryService.getModel(id);
            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";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes)).deploy();
            return new Result(true, deployment);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, "失败");
    }


}
