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

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.tree.DefaultText;

import java.util.Map;

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

    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");
        } catch (Exception e) {
            e.printStackTrace();
            map.clear();
        }
        return map;
    }

    public static String element2Str(Element rootElement) {
        StringBuffer sbf = new StringBuffer();
        if (rootElement != null) {
            rootElement.content().forEach(ctt -> {
                if (ctt.getClass().getName().equals("org.dom4j.tree.DefaultElement")) {
                    Element sonElement = (Element) ctt;
                    if (sonElement.hasContent()) {
                        sbf.append(element2Str(sonElement));
                    }
                } else {
                    DefaultText sonText = (DefaultText) ctt;
                    sbf.append(sonText.getText());
                }
            });
        }
        return sbf.toString();
    }

    public static String bcXmlAna(String xml) {
        String ret = null;
        try {
            Document doc = DocumentHelper.parseText(xml);
            Element root = doc.getRootElement();
            Element titleElement = root.element("病历记录标题");
            root.remove(titleElement);
            Element timeElement = root.element("病历记录时间");
            root.remove(timeElement);
            ret = "原始文本：" + element2Str(root);
            if (titleElement != null) {
                ret = "病历记录标题：" + titleElement.getTextTrim() + " " + ret;
            }
            if (timeElement != null) {
                ret = "病历记录时间：" + timeElement.getTextTrim() + " " + ret;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return ret;
    }

    public static String xml2Txt(String xml) {
        String ret = null;
        try {
            Document doc = DocumentHelper.parseText(xml);
            Element root = doc.getRootElement();
            ret = element2Str(root);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return ret;
    }

}