//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.flowable.ui.modeler.service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.cmmn.converter.CmmnXmlConverter;
import org.flowable.cmmn.editor.json.converter.CmmnJsonConverter;
import org.flowable.cmmn.editor.json.converter.util.CmmnModelJsonConverterUtil;
import org.flowable.cmmn.model.CmmnModel;
import org.flowable.editor.language.json.converter.BpmnJsonConverter;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.flowable.editor.language.json.converter.util.JsonConverterUtil;
import org.flowable.form.model.SimpleFormModel;
import org.flowable.idm.api.User;
import org.flowable.ui.common.security.SecurityUtils;
import org.flowable.ui.common.service.exception.BadRequestException;
import org.flowable.ui.common.service.exception.InternalServerErrorException;
import org.flowable.ui.common.service.exception.NotFoundException;
import org.flowable.ui.common.util.XmlUtil;
import org.flowable.ui.modeler.domain.*;
import org.flowable.ui.modeler.model.ModelKeyRepresentation;
import org.flowable.ui.modeler.model.ModelRepresentation;
import org.flowable.ui.modeler.model.ReviveModelResultRepresentation;
import org.flowable.ui.modeler.model.ReviveModelResultRepresentation.UnresolveModelRepresentation;
import org.flowable.ui.modeler.model.decisiontable.DecisionTableDefinitionRepresentation;
import org.flowable.ui.modeler.repository.ModelHistoryRepository;
import org.flowable.ui.modeler.repository.ModelRelationRepository;
import org.flowable.ui.modeler.repository.ModelRepository;
import org.flowable.ui.modeler.serviceapi.ModelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

@Service
@Transactional
public class ModelServiceImpl implements ModelService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ModelServiceImpl.class);
    public static final String NAMESPACE = "http://flowable.org/modeler";
    protected static final String PROCESS_NOT_FOUND_MESSAGE_KEY = "PROCESS.ERROR.NOT-FOUND";
    @Autowired
    protected ModelImageService modelImageService;
    @Autowired
    protected ModelRepository modelRepository;
    @Autowired
    protected ModelHistoryRepository modelHistoryRepository;
    @Autowired
    protected ModelRelationRepository modelRelationRepository;
    @Autowired
    protected ObjectMapper objectMapper;
    protected BpmnJsonConverter bpmnJsonConverter = new BpmnJsonConverter();
    protected BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
    protected CmmnJsonConverter cmmnJsonConverter = new CmmnJsonConverter();
    protected CmmnXmlConverter cmmnXMLConverter = new CmmnXmlConverter();

    public ModelServiceImpl() {
        System.out.println("zlmy_boot ModelServiceImpl ModelServiceImpl()");
    }

    public Model getModel(String modelId) {
        System.out.println("zlmy_boot ModelServiceImpl getModel()");
        Model model = this.modelRepository.get(modelId);
        if (model == null) {
            NotFoundException modelNotFound = new NotFoundException("No model found with the given id: " + modelId);
            modelNotFound.setMessageKey("PROCESS.ERROR.NOT-FOUND");
            throw modelNotFound;
        } else {
            return model;
        }
    }

    public ModelRepresentation getModelRepresentation(String modelId) {
        System.out.println("zlmy_boot ModelServiceImpl getModelRepresentation()");
        Model model = this.getModel(modelId);
        return new ModelRepresentation(model);
    }

    public List<AbstractModel> getModelsByModelType(Integer modelType) {
        System.out.println("zlmy_boot ModelServiceImpl getModelsByModelType()");
        return new ArrayList(this.modelRepository.findByModelType(modelType, "nameAsc"));
    }

    public ModelHistory getModelHistory(String modelId, String modelHistoryId) {
        System.out.println("zlmy_boot ModelServiceImpl getModelHistory()");
        Model model = this.getModel(modelId);
        ModelHistory modelHistory = this.modelHistoryRepository.get(modelHistoryId);
        if (modelHistory != null && modelHistory.getRemovalDate() == null && modelHistory.getModelId().equals(model.getId())) {
            return modelHistory;
        } else {
            throw new NotFoundException("Process model history not found: " + modelHistoryId);
        }
    }

    public byte[] getBpmnXML(AbstractModel model) {
        System.out.println("zlmy_boot ModelServiceImpl getBpmnXML()");
        BpmnModel bpmnModel = this.getBpmnModel(model);
        return this.getBpmnXML(bpmnModel);
    }

    public byte[] getBpmnXML(BpmnModel bpmnModel) {
        System.out.println("zlmy_boot ModelServiceImpl getBpmnXML()");
        Iterator var2 = bpmnModel.getProcesses().iterator();

        while(var2.hasNext()) {
            Process process = (Process)var2.next();
            if (StringUtils.isNotEmpty(process.getId())) {
                char firstCharacter = process.getId().charAt(0);
                if (Character.isDigit(firstCharacter)) {
                    process.setId("a" + process.getId());
                }
            }
        }

        byte[] xmlBytes = this.bpmnXMLConverter.convertToXML(bpmnModel);
        return xmlBytes;
    }

    public byte[] getCmmnXML(AbstractModel model) {
        System.out.println("zlmy_boot ModelServiceImpl getCmmnXML()111");
        CmmnModel cmmnModel = this.getCmmnModel(model);
        return this.getCmmnXML(cmmnModel);
    }

    public byte[] getCmmnXML(CmmnModel cmmnModel) {
        System.out.println("zlmy_boot ModelServiceImpl getCmmnXML222()");
        byte[] xmlBytes = this.cmmnXMLConverter.convertToXML(cmmnModel);
        return xmlBytes;
    }

    public ModelKeyRepresentation validateModelKey(Model model, Integer modelType, String key) {
        System.out.println("zlmy_boot ModelServiceImpl validateModelKey()");
        ModelKeyRepresentation modelKeyResponse = new ModelKeyRepresentation();
        modelKeyResponse.setKey(key);
        List<Model> models = this.modelRepository.findByKeyAndType(key, modelType);
        Iterator var6 = models.iterator();

        while(var6.hasNext()) {
            Model modelInfo = (Model)var6.next();
            if (model == null || !modelInfo.getId().equals(model.getId())) {
                modelKeyResponse.setKeyAlreadyExists(true);
                modelKeyResponse.setId(modelInfo.getId());
                modelKeyResponse.setName(modelInfo.getName());
                break;
            }
        }

        return modelKeyResponse;
    }

    public String createModelJson(ModelRepresentation model) {
        System.out.println("zlmy_boot createModelJson");
        String json = null;
        if (Integer.valueOf(2).equals(model.getModelType())) {
            try {
                json = this.objectMapper.writeValueAsString(new SimpleFormModel());
            } catch (Exception var14) {
                LOGGER.error("Error creating form model", var14);
                throw new InternalServerErrorException("Error creating form");
            }
        } else if (Integer.valueOf(4).equals(model.getModelType())) {
            try {
                DecisionTableDefinitionRepresentation decisionTableDefinition = new DecisionTableDefinitionRepresentation();
                String decisionTableDefinitionKey = model.getName().replaceAll(" ", "");
                decisionTableDefinition.setKey(decisionTableDefinitionKey);
                json = this.objectMapper.writeValueAsString(decisionTableDefinition);
            } catch (Exception var13) {
                LOGGER.error("Error creating decision table model", var13);
                throw new InternalServerErrorException("Error creating decision table");
            }
        } else if (Integer.valueOf(3).equals(model.getModelType())) {
            try {
                json = this.objectMapper.writeValueAsString(new AppDefinition());
            } catch (Exception var12) {
                LOGGER.error("Error creating app definition", var12);
                throw new InternalServerErrorException("Error creating app definition");
            }
        } else {
            ObjectNode propertiesNode;
            ArrayNode childShapeArray;
            ObjectNode childNode;
            ObjectNode boundsNode;
            ObjectNode lowerRightNode;
            ObjectNode upperLeftNode;
            ObjectNode stencilNode;
            ObjectNode editorNode;
            ObjectNode stencilSetNode;
            if (Integer.valueOf(5).equals(model.getModelType())) {
                editorNode = this.objectMapper.createObjectNode();
                editorNode.put("id", "canvas");
                editorNode.put("resourceId", "canvas");
                stencilSetNode = this.objectMapper.createObjectNode();
                stencilSetNode.put("namespace", "http://b3mn.org/stencilset/cmmn1.1#");
                editorNode.set("stencilset", stencilSetNode);
                propertiesNode = this.objectMapper.createObjectNode();
                propertiesNode.put("case_id", model.getKey());
                propertiesNode.put("name", model.getName());
                if (StringUtils.isNotEmpty(model.getDescription())) {
                    propertiesNode.put("documentation", model.getDescription());
                }

                editorNode.set("properties", propertiesNode);
                childShapeArray = this.objectMapper.createArrayNode();
                editorNode.set("childShapes", childShapeArray);
                childNode = this.objectMapper.createObjectNode();
                childShapeArray.add(childNode);
                boundsNode = this.objectMapper.createObjectNode();
                childNode.set("bounds", boundsNode);
                lowerRightNode = this.objectMapper.createObjectNode();
                boundsNode.set("lowerRight", lowerRightNode);
                lowerRightNode.put("x", 758);
                lowerRightNode.put("y", 754);
                upperLeftNode = this.objectMapper.createObjectNode();
                boundsNode.set("upperLeft", upperLeftNode);
                upperLeftNode.put("x", 40);
                upperLeftNode.put("y", 40);
                childNode.set("childShapes", this.objectMapper.createArrayNode());
                childNode.set("dockers", this.objectMapper.createArrayNode());
                childNode.set("outgoing", this.objectMapper.createArrayNode());
                childNode.put("resourceId", "casePlanModel");
                stencilNode = this.objectMapper.createObjectNode();
                childNode.set("stencil", stencilNode);
                stencilNode.put("id", "CasePlanModel");
                json = editorNode.toString();
            } else {
                editorNode = this.objectMapper.createObjectNode();
                editorNode.put("id", "canvas");
                editorNode.put("resourceId", "canvas");
                stencilSetNode = this.objectMapper.createObjectNode();
                stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
                editorNode.set("stencilset", stencilSetNode);
                propertiesNode = this.objectMapper.createObjectNode();
                propertiesNode.put("process_id", model.getKey());
                propertiesNode.put("name", model.getName());
                if (StringUtils.isNotEmpty(model.getDescription())) {
                    propertiesNode.put("documentation", model.getDescription());
                }

                editorNode.set("properties", propertiesNode);
                childShapeArray = this.objectMapper.createArrayNode();
                editorNode.set("childShapes", childShapeArray);
                childNode = this.objectMapper.createObjectNode();
                childShapeArray.add(childNode);
                boundsNode = this.objectMapper.createObjectNode();
                childNode.set("bounds", boundsNode);
                lowerRightNode = this.objectMapper.createObjectNode();
                boundsNode.set("lowerRight", lowerRightNode);
                lowerRightNode.put("x", 130);
                lowerRightNode.put("y", 193);
                upperLeftNode = this.objectMapper.createObjectNode();
                boundsNode.set("upperLeft", upperLeftNode);
                upperLeftNode.put("x", 100);
                upperLeftNode.put("y", 163);
                childNode.set("childShapes", this.objectMapper.createArrayNode());
                childNode.set("dockers", this.objectMapper.createArrayNode());
                childNode.set("outgoing", this.objectMapper.createArrayNode());
                childNode.put("resourceId", "startEvent1");
                stencilNode = this.objectMapper.createObjectNode();
                childNode.set("stencil", stencilNode);
                stencilNode.put("id", "StartNoneEvent");
                json = editorNode.toString();
            }
        }

        return json;
    }

    public Model createModel(Model newModel, User createdBy) {
        System.out.println("zlmy_boot ModelServiceImpl createModel()1111");
        newModel.setVersion(1);
        newModel.setCreated(Calendar.getInstance().getTime());
        newModel.setCreatedBy(createdBy.getId());
        newModel.setLastUpdated(Calendar.getInstance().getTime());
        newModel.setLastUpdatedBy(createdBy.getId());
        this.persistModel(newModel);
        return newModel;
    }

    public Model createModel(ModelRepresentation model, String editorJson, User createdBy) {
        System.out.println("zlmy_boot ModelServiceImpl createModel()22222");
        System.out.println("ModelsResourceAspect joinPoint "+ JSON.toJSONString(createdBy));

        Model newModel = new Model();
        newModel.setVersion(1);
        newModel.setName(model.getName());
        newModel.setKey(model.getKey());
        newModel.setModelType(model.getModelType());
        newModel.setCreated(Calendar.getInstance().getTime());
        newModel.setCreatedBy(createdBy.getId());
        newModel.setDescription(model.getDescription());
        newModel.setModelEditorJson(editorJson);
        newModel.setLastUpdated(Calendar.getInstance().getTime());
        newModel.setLastUpdatedBy(createdBy.getId());
        newModel.setTenantId(model.getTenantId());
        this.persistModel(newModel);
        return newModel;
    }

    public ModelRepresentation importNewVersion(String modelId, String fileName, InputStream modelStream) {
        System.out.println("zlmy_boot ModelServiceImpl importNewVersion()");
        Model processModel = this.getModel(modelId);
        User currentUser = SecurityUtils.getCurrentUserObject();
        if (fileName == null || !fileName.endsWith(".bpmn") && !fileName.endsWith(".bpmn20.xml")) {
            throw new BadRequestException("Invalid file name, only .bpmn and .bpmn20.xml files are supported not " + fileName);
        } else {
            try {
                XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
                InputStreamReader xmlIn = new InputStreamReader(modelStream, "UTF-8");
                XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
                BpmnModel bpmnModel = this.bpmnXMLConverter.convertToBpmnModel(xtr);
                if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
                    throw new BadRequestException("No process found in definition " + fileName);
                } else if (bpmnModel.getLocationMap().size() == 0) {
                    throw new BadRequestException("No required BPMN DI information found in definition " + fileName);
                } else {
                    ObjectNode modelNode = this.bpmnJsonConverter.convertToJson(bpmnModel);
                    AbstractModel savedModel = this.saveModel(modelId, processModel.getName(), processModel.getKey(), processModel.getDescription(), modelNode.toString(), true, "Version import via REST service", currentUser);
                    return new ModelRepresentation(savedModel);
                }
            } catch (BadRequestException var12) {
                throw var12;
            } catch (Exception var13) {
                throw new BadRequestException("Import failed for " + fileName + ", error message " + var13.getMessage());
            }
        }
    }

    public Model createNewModelVersion(Model modelObject, String comment, User updatedBy) {
        System.out.println("zlmy_boot ModelServiceImpl createNewModelVersion()");
        return (Model)this.internalCreateNewModelVersion(modelObject, comment, updatedBy, false);
    }

    public ModelHistory createNewModelVersionAndReturnModelHistory(Model modelObject, String comment, User updatedBy) {
        System.out.println("zlmy_boot ModelServiceImpl createNewModelVersionAndReturnModelHistory()");
        return (ModelHistory)this.internalCreateNewModelVersion(modelObject, comment, updatedBy, true);
    }

    protected AbstractModel internalCreateNewModelVersion(Model modelObject, String comment, User updatedBy, boolean returnModelHistory) {
        System.out.println("zlmy_boot ModelServiceImpl internalCreateNewModelVersion()");
        modelObject.setLastUpdated(new Date());
        modelObject.setLastUpdatedBy(updatedBy.getId());
        modelObject.setComment(comment);
        ModelHistory historyModel = this.createNewModelhistory(modelObject);
        this.persistModelHistory(historyModel);
        modelObject.setVersion(modelObject.getVersion() + 1);
        this.persistModel(modelObject);
        return (AbstractModel)(returnModelHistory ? historyModel : modelObject);
    }

    public Model saveModel(Model modelObject) {

        System.out.println("zlmy_boot ModelServiceImpl saveModel()1111");

        return this.persistModel(modelObject);
    }

    public Model saveModel(Model modelObject, String editorJson, byte[] imageBytes, boolean newVersion, String newVersionComment, User updatedBy) {
        System.out.println("zlmy_boot ModelServiceImpl saveModel()2222");
        return this.internalSave(modelObject.getName(), modelObject.getKey(), modelObject.getDescription(), editorJson, newVersion, newVersionComment, imageBytes, updatedBy, modelObject);
    }

    public Model saveModel(String modelId, String name, String key, String description, String editorJson, boolean newVersion, String newVersionComment, User updatedBy) {
        System.out.println("zlmy_boot ModelServiceImpl saveModel()33333");
        Model modelObject = this.modelRepository.get(modelId);
        return this.internalSave(name, key, description, editorJson, newVersion, newVersionComment, (byte[])null, updatedBy, modelObject);
    }

    protected Model internalSave(String name, String key, String description, String editorJson, boolean newVersion, String newVersionComment, byte[] imageBytes, User updatedBy, Model modelObject) {
        System.out.println("zlmy_boot ModelServiceImpl internalSave()");
        if (!newVersion) {
            modelObject.setLastUpdated(new Date());
            modelObject.setLastUpdatedBy(updatedBy.getId());
            modelObject.setName(name);
            modelObject.setKey(key);
            modelObject.setDescription(description);
            modelObject.setModelEditorJson(editorJson);
            if (imageBytes != null) {
                modelObject.setThumbnail(imageBytes);
            }
        } else {
            ModelHistory historyModel = this.createNewModelhistory(modelObject);
            this.persistModelHistory(historyModel);
            modelObject.setVersion(modelObject.getVersion() + 1);
            modelObject.setLastUpdated(new Date());
            modelObject.setLastUpdatedBy(updatedBy.getId());
            modelObject.setName(name);
            modelObject.setKey(key);
            modelObject.setDescription(description);
            modelObject.setModelEditorJson(editorJson);
            modelObject.setComment(newVersionComment);
            if (imageBytes != null) {
                modelObject.setThumbnail(imageBytes);
            }
        }

        return this.persistModel(modelObject);
    }

    public void deleteModel(String modelId) {
        System.out.println("zlmy_boot ModelServiceImpl deleteModel()");
        Model model = this.modelRepository.get(modelId);
        if (model == null) {
            throw new IllegalArgumentException("No model found with id: " + modelId);
        } else {
            List<ModelHistory> history = this.modelHistoryRepository.findByModelId(model.getId());
            ModelHistory historyModel = this.createNewModelhistory(model);
            historyModel.setRemovalDate(Calendar.getInstance().getTime());
            this.persistModelHistory(historyModel);
            this.deleteModelAndChildren(model);
        }
    }

    protected void deleteModelAndChildren(Model model) {
        System.out.println("zlmy_boot ModelServiceImpl deleteModelAndChildren()");
        List<Model> allModels = new ArrayList();
        this.internalDeleteModelAndChildren(model, allModels);
        Iterator var3 = allModels.iterator();

        while(var3.hasNext()) {
            Model modelToDelete = (Model)var3.next();
            this.modelRepository.delete(modelToDelete);
        }

    }

    protected void internalDeleteModelAndChildren(Model model, List<Model> allModels) {
        System.out.println("zlmy_boot ModelServiceImpl internalDeleteModelAndChildren()");
        this.modelRelationRepository.deleteModelRelationsForParentModel(model.getId());
        allModels.add(model);
    }

    public ReviveModelResultRepresentation reviveProcessModelHistory(ModelHistory modelHistory, User user, String newVersionComment) {
        System.out.println("zlmy_boot ModelServiceImpl reviveProcessModelHistory()");

        Model latestModel = this.modelRepository.get(modelHistory.getModelId());
        if (latestModel == null) {
            throw new IllegalArgumentException("No process model found with id: " + modelHistory.getModelId());
        } else {
            ModelHistory latestModelHistory = this.createNewModelhistory(latestModel);
            this.persistModelHistory(latestModelHistory);
            latestModel.setVersion(latestModel.getVersion() + 1);
            latestModel.setLastUpdated(new Date());
            latestModel.setLastUpdatedBy(user.getId());
            latestModel.setName(modelHistory.getName());
            latestModel.setKey(modelHistory.getKey());
            latestModel.setDescription(modelHistory.getDescription());
            latestModel.setModelEditorJson(modelHistory.getModelEditorJson());
            latestModel.setModelType(modelHistory.getModelType());
            latestModel.setComment(newVersionComment);
            this.persistModel(latestModel);
            ReviveModelResultRepresentation result = new ReviveModelResultRepresentation();
            if (latestModel.getModelType() == 3 && StringUtils.isNotEmpty(latestModel.getModelEditorJson())) {
                try {
                    AppDefinition appDefinition = (AppDefinition)this.objectMapper.readValue(latestModel.getModelEditorJson(), AppDefinition.class);
                    Iterator var8 = appDefinition.getModels().iterator();

                    while(var8.hasNext()) {
                        AppModelDefinition appModelDefinition = (AppModelDefinition)var8.next();
                        if (this.modelRepository.get(appModelDefinition.getId()) == null) {
                            result.getUnresolvedModels().add(new UnresolveModelRepresentation(appModelDefinition.getId(), appModelDefinition.getName(), appModelDefinition.getLastUpdatedBy()));
                        }
                    }
                } catch (Exception var10) {
                    LOGGER.error("Could not deserialize app model json (id = {})", latestModel.getId(), var10);
                }
            }

            return result;
        }
    }

    public BpmnModel getBpmnModel(AbstractModel model) {
        System.out.println("zlmy_boot ModelServiceImpl getBpmnModel()111");

        BpmnModel bpmnModel = null;

        try {
            Map<String, Model> formMap = new HashMap();
            Map<String, Model> decisionTableMap = new HashMap();
            List<Model> referencedModels = this.modelRepository.findByParentModelId(model.getId());
            Iterator var6 = referencedModels.iterator();

            while(var6.hasNext()) {
                Model childModel = (Model)var6.next();
                if (2 == childModel.getModelType()) {
                    formMap.put(childModel.getId(), childModel);
                } else if (4 == childModel.getModelType()) {
                    decisionTableMap.put(childModel.getId(), childModel);
                }
            }

            bpmnModel = this.getBpmnModel(model, formMap, decisionTableMap);
            return bpmnModel;
        } catch (Exception var8) {
            LOGGER.error("Could not generate BPMN 2.0 model for {}", model.getId(), var8);
            throw new InternalServerErrorException("Could not generate BPMN 2.0 model");
        }
    }

    public BpmnModel getBpmnModel(AbstractModel model, Map<String, Model> formMap, Map<String, Model> decisionTableMap) {
        System.out.println("zlmy_boot ModelServiceImpl getBpmnModel()222");
        try {
            ObjectNode editorJsonNode = (ObjectNode)this.objectMapper.readTree(model.getModelEditorJson());
            Map<String, String> formKeyMap = new HashMap();
            Iterator var6 = formMap.values().iterator();

            while(var6.hasNext()) {
                Model formModel = (Model)var6.next();
                formKeyMap.put(formModel.getId(), formModel.getKey());
            }

            Map<String, String> decisionTableKeyMap = new HashMap();
            Iterator var11 = decisionTableMap.values().iterator();

            while(var11.hasNext()) {
                Model decisionTableModel = (Model)var11.next();
                decisionTableKeyMap.put(decisionTableModel.getId(), decisionTableModel.getKey());
            }

            return this.bpmnJsonConverter.convertToBpmnModel(editorJsonNode, formKeyMap, decisionTableKeyMap);
        } catch (Exception var9) {
            LOGGER.error("Could not generate BPMN 2.0 model for {}", model.getId(), var9);
            throw new InternalServerErrorException("Could not generate BPMN 2.0 model");
        }
    }

    public CmmnModel getCmmnModel(AbstractModel model) {
        CmmnModel cmmnModel = null;

        try {
            Map<String, Model> formMap = new HashMap();
            Map<String, Model> decisionTableMap = new HashMap();
            Map<String, Model> caseModelMap = new HashMap();
            Map<String, Model> processModelMap = new HashMap();
            List<Model> referencedModels = this.modelRepository.findByParentModelId(model.getId());
            Iterator var8 = referencedModels.iterator();

            while(var8.hasNext()) {
                Model childModel = (Model)var8.next();
                if (2 == childModel.getModelType()) {
                    formMap.put(childModel.getId(), childModel);
                } else if (4 == childModel.getModelType()) {
                    decisionTableMap.put(childModel.getId(), childModel);
                } else if (5 == childModel.getModelType()) {
                    caseModelMap.put(childModel.getId(), childModel);
                } else if (0 == childModel.getModelType()) {
                    processModelMap.put(childModel.getId(), childModel);
                }
            }

            cmmnModel = this.getCmmnModel(model, formMap, decisionTableMap, caseModelMap, processModelMap);
            return cmmnModel;
        } catch (Exception var10) {
            LOGGER.error("Could not generate CMMN model for {}", model.getId(), var10);
            throw new InternalServerErrorException("Could not generate CMMN model");
        }
    }

    public CmmnModel getCmmnModel(AbstractModel model, Map<String, Model> formMap, Map<String, Model> decisionTableMap, Map<String, Model> caseModelMap, Map<String, Model> processModelMap) {
        try {
            ObjectNode editorJsonNode = (ObjectNode)this.objectMapper.readTree(model.getModelEditorJson());
            Map<String, String> formKeyMap = this.convertToModelKeyMap(formMap);
            Map<String, String> decisionTableKeyMap = this.convertToModelKeyMap(decisionTableMap);
            Map<String, String> caseModelKeyMap = this.convertToModelKeyMap(caseModelMap);
            Map<String, String> processModelKeyMap = this.convertToModelKeyMap(processModelMap);
            return this.cmmnJsonConverter.convertToCmmnModel(editorJsonNode, formKeyMap, decisionTableKeyMap, caseModelKeyMap, processModelKeyMap);
        } catch (Exception var11) {
            LOGGER.error("Could not generate CMMN model for {}", model.getId(), var11);
            throw new InternalServerErrorException("Could not generate CMMN model");
        }
    }

    protected void addOrUpdateExtensionElement(String name, String value, UserTask userTask) {
        System.out.println("zlmy_boot ModelServiceImpl addOrUpdateExtensionElement()222");

        List<ExtensionElement> extensionElements = (List)userTask.getExtensionElements().get(name);
        ExtensionElement extensionElement;
        if (CollectionUtils.isNotEmpty(extensionElements)) {
            extensionElement = (ExtensionElement)extensionElements.get(0);
        } else {
            extensionElement = new ExtensionElement();
        }

        extensionElement.setNamespace("http://flowable.org/modeler");
        extensionElement.setNamespacePrefix("modeler");
        extensionElement.setName(name);
        extensionElement.setElementText(value);
        if (CollectionUtils.isEmpty(extensionElements)) {
            userTask.addExtensionElement(extensionElement);
        }

    }

    public Long getModelCountForUser(User user, int modelType) {
        System.out.println("zlmy_boot ModelServiceImpl getModelCountForUser()");

        return this.modelRepository.countByModelTypeAndCreatedBy(modelType, user.getId());
    }

    protected Model persistModel(Model model) {
        System.out.println("zlmy_boot ModelServiceImpl persistModel()");

        if (StringUtils.isNotEmpty(model.getModelEditorJson())) {
            ObjectNode jsonNode = null;

            try {
                jsonNode = (ObjectNode)this.objectMapper.readTree(model.getModelEditorJson());
            } catch (Exception var4) {
                LOGGER.error("Could not deserialize json model", var4);
                throw new InternalServerErrorException("Could not deserialize json model");
            }

            byte[] thumbnail;
            if (model.getModelType() != null && model.getModelType() != 0) {
                if (model.getModelType() == 5) {
                    thumbnail = this.modelImageService.generateCmmnThumbnailImage(model, jsonNode);
                    if (thumbnail != null) {
                        model.setThumbnail(thumbnail);
                    }

                    this.modelRepository.save(model);
                    this.handleCmmnFormModelRelations(model, jsonNode);
                    this.handleCmmnDecisionModelRelations(model, jsonNode);
                    this.handleCmmnCaseModelRelations(model, jsonNode);
                    this.handleCmmnProcessModelRelations(model, jsonNode);
                } else if (model.getModelType() != 2 && model.getModelType() != 4) {
                    if (model.getModelType() == 3) {
                        this.modelRepository.save(model);
                        this.handleAppModelProcessRelations(model, jsonNode);
                    }
                } else {
                    jsonNode.put("name", model.getName());
                    jsonNode.put("key", model.getKey());
                    this.modelRepository.save(model);
                }
            } else {
                thumbnail = this.modelImageService.generateThumbnailImage(model, jsonNode);
                if (thumbnail != null) {
                    model.setThumbnail(thumbnail);
                }

                this.modelRepository.save(model);
                this.handleBpmnProcessFormModelRelations(model, jsonNode);
                this.handleBpmnProcessDecisionTaskModelRelations(model, jsonNode);
            }
        }

        return model;
    }

    protected void persistModelHistory(ModelHistory modelHistory) {

        this.modelHistoryRepository.save(modelHistory);
    }

    protected void handleBpmnProcessFormModelRelations(AbstractModel bpmnProcessModel, ObjectNode editorJsonNode) {
        System.out.println("zlmy_boot ModelServiceImpl handleBpmnProcessFormModelRelations()");
        List<JsonNode> formReferenceNodes = JsonConverterUtil.filterOutJsonNodes(JsonConverterUtil.getBpmnProcessModelFormReferences(editorJsonNode));
        Set<String> formIds = JsonConverterUtil.gatherStringPropertyFromJsonNodes(formReferenceNodes, "id");
        this.handleModelRelations(bpmnProcessModel, formIds, "form-model");
    }

    protected void handleBpmnProcessDecisionTaskModelRelations(AbstractModel bpmnProcessModel, ObjectNode editorJsonNode) {

        List<JsonNode> decisionTableNodes = JsonConverterUtil.filterOutJsonNodes(JsonConverterUtil.getBpmnProcessModelDecisionTableReferences(editorJsonNode));
        Set<String> decisionTableIds = JsonConverterUtil.gatherStringPropertyFromJsonNodes(decisionTableNodes, "id");
        this.handleModelRelations(bpmnProcessModel, decisionTableIds, "decision-table-model");
    }

    protected void handleCmmnFormModelRelations(AbstractModel caseModel, ObjectNode editorJsonNode) {
        List<JsonNode> formReferenceNodes = CmmnModelJsonConverterUtil.filterOutJsonNodes(CmmnModelJsonConverterUtil.getCmmnModelFormReferences(editorJsonNode));
        Set<String> formIds = JsonConverterUtil.gatherStringPropertyFromJsonNodes(formReferenceNodes, "id");
        this.handleModelRelations(caseModel, formIds, "form-model");
    }

    protected void handleCmmnDecisionModelRelations(AbstractModel caseModel, ObjectNode editorJsonNode) {
        List<JsonNode> processReferenceNodes = CmmnModelJsonConverterUtil.filterOutJsonNodes(CmmnModelJsonConverterUtil.getCmmnModelDecisionTableReferences(editorJsonNode));
        Set<String> processModelIds = JsonConverterUtil.gatherStringPropertyFromJsonNodes(processReferenceNodes, "id");
        this.handleModelRelations(caseModel, processModelIds, "decision-table-model");
    }

    protected void handleCmmnCaseModelRelations(AbstractModel caseModel, ObjectNode editorJsonNode) {
        List<JsonNode> caseReferenceNodes = CmmnModelJsonConverterUtil.filterOutJsonNodes(CmmnModelJsonConverterUtil.getCmmnModelCaseReferences(editorJsonNode));
        Set<String> caseModelIds = JsonConverterUtil.gatherStringPropertyFromJsonNodes(caseReferenceNodes, "id");
        this.handleModelRelations(caseModel, caseModelIds, "case-model-child");
    }

    protected void handleCmmnProcessModelRelations(AbstractModel caseModel, ObjectNode editorJsonNode) {
        List<JsonNode> processReferenceNodes = CmmnModelJsonConverterUtil.filterOutJsonNodes(CmmnModelJsonConverterUtil.getCmmnModelProcessReferences(editorJsonNode));
        Set<String> processModelIds = JsonConverterUtil.gatherStringPropertyFromJsonNodes(processReferenceNodes, "id");
        this.handleModelRelations(caseModel, processModelIds, "process-model-child");
    }

    protected void handleAppModelProcessRelations(AbstractModel appModel, ObjectNode appModelJsonNode) {
        Set<String> processModelIds = JsonConverterUtil.getAppModelReferencedModelIds(appModelJsonNode);
        this.handleModelRelations(appModel, processModelIds, "process-model");
    }

    protected void handleModelRelations(AbstractModel bpmnProcessModel, Set<String> idsReferencedInJson, String relationshipType) {
        System.out.println("zlmy_boot ModelServiceImpl handleModelRelations()");

        List<ModelRelation> persistedModelRelations = this.modelRelationRepository.findByParentModelIdAndType(bpmnProcessModel.getId(), relationshipType);
        if (idsReferencedInJson != null && idsReferencedInJson.size() != 0) {
            Set<String> alreadyPersistedModelIds = new HashSet(persistedModelRelations.size());
            Iterator var9 = persistedModelRelations.iterator();

            while(var9.hasNext()) {
                ModelRelation persistedModelRelation = (ModelRelation)var9.next();
                if (!idsReferencedInJson.contains(persistedModelRelation.getModelId())) {
                    this.modelRelationRepository.delete(persistedModelRelation);
                } else {
                    alreadyPersistedModelIds.add(persistedModelRelation.getModelId());
                }
            }

            var9 = idsReferencedInJson.iterator();

            while(var9.hasNext()) {
                String idReferencedInJson = (String)var9.next();
                if (!alreadyPersistedModelIds.contains(idReferencedInJson) && this.modelRepository.get(idReferencedInJson) != null) {
                    this.modelRelationRepository.save(new ModelRelation(bpmnProcessModel.getId(), idReferencedInJson, relationshipType));
                }
            }

        } else {
            Iterator var5 = persistedModelRelations.iterator();

            while(var5.hasNext()) {
                ModelRelation modelRelation = (ModelRelation)var5.next();
                this.modelRelationRepository.delete(modelRelation);
            }

        }
    }

    protected ModelHistory createNewModelhistory(Model model) {
        System.out.println("zlmy_boot ModelServiceImpl handleModelRelations()");

        ModelHistory historyModel = new ModelHistory();
        historyModel.setName(model.getName());
        historyModel.setKey(model.getKey());
        historyModel.setDescription(model.getDescription());
        historyModel.setCreated(model.getCreated());
        historyModel.setLastUpdated(model.getLastUpdated());
        historyModel.setCreatedBy(model.getCreatedBy());
        historyModel.setLastUpdatedBy(model.getLastUpdatedBy());
        historyModel.setModelEditorJson(model.getModelEditorJson());
        historyModel.setModelType(model.getModelType());
        historyModel.setVersion(model.getVersion());
        historyModel.setModelId(model.getId());
        historyModel.setComment(model.getComment());
        historyModel.setTenantId(model.getTenantId());
        return historyModel;
    }

    protected void populateModelBasedOnHistory(Model model, ModelHistory basedOn) {
        model.setName(basedOn.getName());
        model.setKey(basedOn.getKey());
        model.setDescription(basedOn.getDescription());
        model.setCreated(basedOn.getCreated());
        model.setLastUpdated(basedOn.getLastUpdated());
        model.setCreatedBy(basedOn.getCreatedBy());
        model.setLastUpdatedBy(basedOn.getLastUpdatedBy());
        model.setModelEditorJson(basedOn.getModelEditorJson());
        model.setModelType(basedOn.getModelType());
        model.setVersion(basedOn.getVersion());
        model.setComment(basedOn.getComment());
        model.setTenantId(basedOn.getTenantId());
    }

    protected Map<String, String> convertToModelKeyMap(Map<String, Model> modelMap) {
        System.out.println("zlmy_boot ModelServiceImpl convertToModelKeyMap()");

        Map<String, String> modelKeyMap = new HashMap();
        if (modelMap != null) {
            Iterator var3 = modelMap.values().iterator();

            while(var3.hasNext()) {
                Model formModel = (Model)var3.next();
                modelKeyMap.put(formModel.getId(), formModel.getKey());
            }
        }

        return modelKeyMap;
    }
}
