package com.huigou.explorer.converters.bpmn;

import com.alibaba.fastjson.JSONArray;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGraphModel;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.Process;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

/**
 * @author yonghuan
 */
public class ProcessConverter implements ElementConverter {

    private ActivitiListenerParser activitiListenerParser;

    public void setActivitiListenerParser(ActivitiListenerParser activitiListenerParser) {
        this.activitiListenerParser = activitiListenerParser;
    }

    @Override
    public boolean supports(Object mxElement) {
        return mxElement instanceof mxGraphModel;
    }

    @Override
    public void convert(BpmnModel bpmnModel, mxGraphModel graphModel, Object mxElement) {
        mxGraphModel model = (mxGraphModel) mxElement;
        mxCell rootCell = (mxCell) model.getRoot();
        Process process = new Process();
        process.setId(rootCell.getAttribute("code"));
        process.setName(rootCell.getAttribute("label"));
        Optional.ofNullable(rootCell.getAttribute("executionListeners"))
                .filter(StringUtils::isNotBlank)
                .map(JSONArray::parseArray)
                .map(activitiListenerParser::parse)
                .ifPresent(executionListeners -> process.setExecutionListeners(executionListeners));
        // 针对流程绑定自定义表单，将formNo保存到流程定义的field中。
        // TODO 后期考虑优化实现方式
        String formNo = rootCell.getAttribute("formNo");
        if (StringUtils.isNotBlank(formNo)) {
            addFieldExtensionElement(process, "formNo", formNo);
        }
        bpmnModel.addProcess(process);
    }
}
