package com.zt.plat.module.qms.resource.material.utils;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

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

@Slf4j
public class BpmnXmlUtil {

    /**
     * 解析 BPMN XML 中的节点扩展字段
     *
     * @param bpmnXml BPMN XML 字符串
     * @return Map<节点 ID, Map<字段名，字段值>>
     */
    public static Map<String, Map<String, String>> parseBpmnFieldExtensions(String bpmnXml) {
        Map<String, Map<String, String>> nodeFieldMap = new HashMap<>();

        try {
            Document document = DocumentHelper.parseText(bpmnXml);
            Element root = document.getRootElement();

            // 查找所有的 userTask 节点
            List<Element> userTasks = findElementsByName(root, "userTask");
            for (Element userTask : userTasks) {
                String taskId = userTask.attributeValue("id");
                Map<String, String> fieldMap = new HashMap<>();

                // 查找所有 executionListener 下的 field
                List<Element> executionListeners = findElementsByName(userTask, "executionListener");
                for (Element listener : executionListeners) {
                    List<Element> fields = listener.elements("field");
                    for (Element field : fields) {
                        String fieldName = field.attributeValue("name");
                        String fieldValue = extractFieldValue(field);
                        if (fieldValue != null) {
                            fieldMap.put(fieldName, fieldValue);
                        }
                    }
                }

                if (!fieldMap.isEmpty()) {
                    nodeFieldMap.put(taskId, fieldMap);
                }
            }
        } catch (Exception e) {
            log.error("解析 BPMN XML 失败：{}", e.getMessage());
        }

        return nodeFieldMap;
    }

    /**
     * 递归查找指定名称的元素
     *
     */
    private static List<Element> findElementsByName(Element root, String elementName) {
        List<Element> result = new ArrayList<>();
        findElementsRecursive(root, elementName, result);
        return result;
    }

    private static void findElementsRecursive(Element element, String elementName, List<Element> result) {
        if (element.getName().equals(elementName)) {
            result.add(element);
        }
        for (Element child : element.elements()) {
            findElementsRecursive(child, elementName, result);
        }
    }

    /**
     * 提取 field 的值，支持 string 和 expression 两种类型
     */
    private static String extractFieldValue(Element field) {
        // 尝试获取 string 类型的值
        Element stringElement = field.element("string");
        if (stringElement != null) {
            return stringElement.getTextTrim();
        }

        // 尝试获取 expression 类型的值
        Element expressionElement = field.element("expression");
        if (expressionElement != null) {
            return expressionElement.getTextTrim();
        }

        return null;
    }
}
