package com.lantone.qc.trans.beilun.util.ez.util;

import com.google.common.collect.Maps;
import com.lantone.qc.dbanaly.facade.yiwu.util.MapUtil;
import com.lantone.qc.pub.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description:
 * @author: HUJING
 * @time: 2021/1/4 14:30
 */
@Slf4j
public class EzXmlUtil {

    public static Map<String, String> analysis(String xml) throws Exception {
        Map<String, String> map = Maps.newLinkedHashMap();
        try {
            Document doc = DocumentHelper.parseText(bom(xml));
            Element rootElement = doc.getRootElement();
            findAllNodes(rootElement, map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("xml解析错误：" + e.getMessage());
        }
        return map;
    }

    /**
     * 从指定节点开始,向下寻找所有节点 ，包括其子节点<br/>
     *
     * @param node 所指定的节点
     */
    public static void findAllNodes(Element node, Map<String, String> map) {

        putNode(node, map);

        // 递归遍历当前节点所有的子节点
        List<Element> listElement = node.elements();

        // 遍历所有一级子节点
        for (Element e : listElement) {
            findAllNodes(e, map);// 递归
        }
    }

    /**
     * 存放节点，不包括其子节点
     *
     * @param node 所指定的节点
     */
    public static void putNode(Element node, Map<String, String> map) {
        String labelName = node.getName();
        List<Attribute> listAttr = node.attributes();// 所有属性
        for (Attribute attr : listAttr) {// 遍历所有属性
            //String name = attr.getName();// 属性名称
            if (("fieldelem".equals(labelName)) && StringUtil.isNotBlank(attr.getValue())) {
                String fieldelemKey = attr.getValue();// 属性的值
                String text = node.getStringValue();
                map.put(fieldelemKey, text);
            }
            if ("section".equals(labelName)) {
                List<Element> content = node.content();
                if (content.size() > 0) {
                    Element firstEle = content.get(0);
                    String key = firstEle.getStringValue();
                    if (key.endsWith("：")) {
                        key = key.substring(0, key.length() - 1);
                    }
                    String value = "";
                    for (int i = 1; i < content.size(); i++) {
                        String v = content.get(i).getStringValue();
                        value += v + " ";
                    }
                    map.put(key, value);
                }
            }
        }
    }

    public static String bom(String result) {
        if (null != result && !"".equals(result)) {
            if (result.contains("<") && result.lastIndexOf(">") != -1 && result.lastIndexOf(">") > result.indexOf("<")) {
                result = result.substring(result.indexOf("<"), result.lastIndexOf(">") + 1);
            }
        }
        return result;
    }

    public static String elementTxt(Node node) {
        if (node != null) {
            return StringUtil.removeBlank(node.getStringValue());
        } else {
            return "";
        }
    }

    /**
     * 根据给定key映射
     *
     * @param sourceMap
     * @param keyContrasts
     * @return
     */
    public static Map<String, String> mapKeyContrast(Map<String, String> sourceMap, List<String> keyContrasts) {
        Map<String, String> retMap = Maps.newHashMap();
        mapKeyContrastCommon(sourceMap, keyContrasts, retMap);
        return retMap;
    }

    public static void mapKeyContrastCommon(Map sourceMap, List<String> keyContrasts, Map<String, String> retMap) {
        Map<String, String> sourceMap_ = MapUtil.copyMap(sourceMap);
        String[] arry = null;
        String sourceKey = null, targetKey;
        Set<String> removeKey = new HashSet<>();
        for (String keyContrast : keyContrasts) {
            arry = keyContrast.split("=");
            sourceKey = arry[0];
            if (arry.length == 1) {
                targetKey = arry[0];
            } else {
                targetKey = arry[1];
            }
            if (StringUtil.isNotBlank(sourceMap_.get(sourceKey))
                    && (!retMap.containsKey(targetKey) || StringUtil.isBlank(retMap.get(targetKey)))) {
                retMap.put(targetKey, sourceMap_.get(sourceKey));
            }
            removeKey.add(sourceKey);
        }
        Set<String> keySet = retMap.keySet();
        for (String key : sourceMap_.keySet()) {
            if (!keySet.contains(key) && !removeKey.contains(key)) { // 如果之前已放过key就不用放了
                retMap.put(key, sourceMap_.get(key));
            }
        }
    }
}