package com.lantone.qc.dbanaly.facade.yiwu;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lantone.qc.pub.util.FileUtil;
import com.lantone.qc.pub.util.StringUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

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

/**
 * @Description: xml解析工具
 * @author: rengb
 * @time: 2020/3/28 14:23
 */
public class YiWuXmlUtil {

    public static Map<String, String> xmlToMap(String xml) {
        Map<String, String> map = Maps.newHashMap();
        try {
            Document doc = DocumentHelper.parseText(xml);
            Element root = (Element) doc.selectSingleNode("//XTextDocument/XElements/Element[@xsi:type='XTextBody']/XElements");
            findElement(root, "XInputField").forEach(i -> {
                xInputField(map, i, null);
            });
            findElement(root, "XTextTable").forEach(tableElement -> {
                String tablePreTxt = getElementPreVal(tableElement);
                findElement(tableElement.element("XElements"), "XTextTableRow").forEach(rowElement -> {
                    findElement(rowElement.element("XElements"), "XTextTableCell").forEach(cellElement -> {
                        findElement(cellElement.element("XElements"), "XInputField").forEach(xInputFieldElement -> {
                            xInputField(map, xInputFieldElement, tablePreTxt);
                        });
                    });
                });
            });
            Element bodyTextElement = (Element) doc.selectSingleNode("//XTextDocument/BodyText");
            String bodyText = bodyTextElement.getText();
            map.put("原始文本", bodyText);
        } catch (Exception e) {
            e.printStackTrace();
            map.clear();
        }
//        map.keySet().forEach(key -> {
//            System.out.println(key + "----" + map.get(key));
//        });
        return map;
    }

    public static List<Element> findElement(Element element, String attual) {
        List<Element> ret = Lists.newArrayList();
        ((List<Element>) (element.elements())).forEach(i -> {
            if (StringUtil.isNotBlank(i.attributeValue("type")) && i.attributeValue("type").equals(attual)) {
                ret.add(i);
            }
        });
        return ret;
    }

    public static void xInputField(Map<String, String> map, Element xInputFieldElement, String tablePreTxt) {
        String value = getXInputFieldValue(xInputFieldElement);
        if (value == null) {
            return;
        }
        String key = getXInputFieldKey(xInputFieldElement, tablePreTxt);
        if (StringUtil.isNotBlank(key)) {
            if (map.containsKey(key)) {
                value = map.get(key) + " " + value;
            }
            map.put(key, value);
        }
    }

    //获取 XInputField 的键
    private static String getXInputFieldKey(Element xInputFieldElement, String tablePreTxt) {
        String key = null;
        String[] elementNames = {"Name","BackgroundText", "ToolTip" };
        for (String elementName : elementNames) {
            key = xInputFieldElement.elementTextTrim(elementName);
            if (StringUtil.isNotBlank(key)) {
                break;
            }
        }
        if (StringUtil.isBlank(key)) {
            key = getElementPreVal(xInputFieldElement);
        }
        if (StringUtil.isBlank(key)) {
            key = tablePreTxt;
        }
        if (StringUtil.isBlank(key)) {
            key = "病历内容";
        }
        return keyHandle(key);
    }

    //获取 XInputField 的值
    private static String getXInputFieldValue(Element xInputFieldElement) {
        String value = null;
        Element innerValueElement = xInputFieldElement.element("InnerValue");
        if (innerValueElement != null) {
            value = innerValueElement.getTextTrim();
        }
        if (StringUtil.isBlank(value)) {
            Element xElementsElement = xInputFieldElement.element("XElements");
            if (xElementsElement != null) {
                List<Element> elements = findElement(xElementsElement, "XString");
                if (elements.size() > 0) {
                    value = "";
                    for (Element element : elements) {
                        Element text = element.element("Text");
                        if (text != null) {
                            value += text.getTextTrim();
                        }
                    }
                }
            }
        }
        return value;
    }

    //获取前面文本信息作为key
    private static String getElementPreVal(Element xInputFieldElement) {
        String ret = "";
        List<Element> sonElements = xInputFieldElement.getParent().elements();
        int index = sonElements.indexOf(xInputFieldElement);
        for (int i = index - 1; i >= 0; i--) {
            Element sonElement = sonElements.get(i);
            if (sonElement.attributeValue("type").equals("XTextTable") || sonElement.attributeValue("type").equals("XInputField")) {
                break;
            }
            if (sonElement.attributeValue("type").equals("XString")) {
                ret = sonElement.elementTextTrim("Text") + ret;
            }
        }
        return ret;
    }

    //针对key的一些特殊处理
    private static String keyHandle(String key) {
        key = StringUtil.removeBlank(key).replaceAll("[：:]", "");
        return key;
    }

    public static void main(String[] args) {
        xmlToMap(FileUtil.fileRead("C:\\Users\\Administrator\\Desktop\\义务\\jiexi\\n5.xml"));
    }

}