package com.manage.util;


import com.alibaba.fastjson.JSON;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class XmlUtils {
    //定义解析器和文档对象
    private SAXReader saxReader;
    private Document document;

    public Document getDocument() {
        return document;
    }

    public XmlUtils(String path) {
        //获取解析器
        saxReader = new SAXReader();
        try {
            //获取文档对象
            document = saxReader.read(path);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public XmlUtils(InputStream path) throws Exception{
        //获取解析器
        saxReader = new SAXReader();
            //获取文档对象
            document = saxReader.read(path);

    }

//    /**
//     * 动态获取节点内容
//     *
//     * @return
//     */
//    public String getElement(String name) {
//        //获取根节点
//        Element root = document.getRootElement();
//        Object directory = FileUtils.getJsonByName("directory");
//        Element current = root;
//        if (directory == null) {
//            throw new RuntimeException("没有定义目录结构");
//        }
//        List<String> directoryArr = (List<String>) directory;
//        for (String dire : directoryArr) {
//            current = current.element(dire);
//        }
//        return current.element(name) == null ? "" : current.element(name).getText();
//    }

    /**
     * 根据路径动态获取节点
     *
     * @return
     */
    public Element getElement(List<String> directory) {
        //获取根节点
        Element root = document.getRootElement();

        Element current = root;
        List<String> directoryArr = directory;
        for (String dire : directoryArr) {
            current = current.element(dire);
        }
        if (current == null) {
            throw new RuntimeException("未找到对应节点");
        }
        return current;
    }

    /**
     * 返回存在的根节点
     */
    public List<Element> getJsonByName(Element root) {
        //获取目录结构
        String path = FileUtils.currentPath();
        //解析json映射文件
        String json = JsonUtils.readJsonFile(path + "\\dataConfig\\homeQualitySet.json");
        Map jsonMap = JSON.parseObject(json, Map.class);
        //判断是否多条
        List<String> basicArr = (List<String>) jsonMap.get("doubleBasic");
//        List<String> directory = (List<String>) jsonMap.get("basicDirectory");
        List<Element> elements = null;
//        Element root = this.getElement(directory);
        for (String basic : basicArr) {
            elements = root.elements(basic);
            if (elements != null && elements.size() > 0) {
                break;
            }
        }
        if (elements == null || elements.size() == 0) {
            //只有一条
//            List<String> rootDirectory = (List<String>) jsonMap.get("directory");
//            root = this.getElement(rootDirectory);
            elements = new ArrayList<>();
            elements.add(root);
        }

        return elements;
    }

    /**
     * 返回数据存在的父节点
     *
     * @return
     */
    public Element getMsgElement() {
        //获取目录结构
        String path = FileUtils.currentPath();
        //解析json映射文件
        String json = JsonUtils.readJsonFile(path + "\\dataConfig\\homeQualitySet.json");
        Map jsonMap = JSON.parseObject(json, Map.class);
        List<String> directory = (List<String>) jsonMap.get("directory");
        Element root = this.getElement(directory);
        return root;
    }

    /**
     * 根据节点名称获取内容
     *
     * @param name 节点名称
     * @return 节点内容
     */
    public String getElementText(String name) {
        //定位根节点
        Element root = document.getRootElement();
        //根据名称定位节点
        Element msg = root.element("Msg");
        if (msg == null) {
            throw new RuntimeException("没有" + "Msg" + "节点");
        }
//        Element patInfo = msg.element(Codes.PAT_INFO.getMessage());
//        if(patInfo==null){
//            throw new RuntimeException("没有"+Codes.PAT_INFO.getMessage()+"节点");
//        }
        Element element = msg.element(name);
        if (element == null) {
            return null;
        }
        //返回节点内容
        return element.getText();
    }

    /**
     * xml转map
     * @param xml
     * @param map
     * @return
     */
    public static Map<String, String> parseXml2Map(String xml, Map<String, String> map) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new StringReader(xml));
            Element root = doc.getRootElement();
            String path = "";
            if (map.containsKey(root.getName().trim())) {
                path = map.get(root.getName().trim());
                map.remove(root.getName().trim());
            }
            for (Iterator i = root.elementIterator(); i.hasNext();) {
                Element element = (Element) i.next();
                if (element.isTextOnly()) {
                    if (path.length() > 0) {
                        map.put(path + element.getName().trim(), element.getTextTrim());
                    } else {
                        map.put(element.getName().trim(), element.getTextTrim());
                    }
                } else {
                    map.put(element.getName().trim(), path+ element.getName().trim() + ".");
                    parseXml2Map(element.asXML(), map);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
