package com.tofly.feesapi.common.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class XmlUtils {

    private static final String mapperUrl = "classpath:mapper/%s";

    /**
     * 根据类的属性名找表的列名（取一个的时候可以使用此方法）
     *
     * @param fileName 类对应的Mapper xml文件
     * @param id       唯一的id
     *                 <p>
     *                 如：resultMap id="BaseResultMap" type="com.chinagas.org.beans.User" 中的id
     *                 </p>
     * @param property 属性名（对应的Java对象属性名）
     * @return
     */
    public static String getMapperColumnByProperty(String fileName, String id, String property) {
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new File(fileName));
            if (document != null) {
                Element root = document.getRootElement();
                if (root != null) {
                    @SuppressWarnings("unchecked")
                    List<Element> resultMaps = root.elements("resultMap");
                    for (Element resultMap : resultMaps) {
                        if (resultMap != null && resultMap.attributeValue("id").equals(id)) {
                            @SuppressWarnings("unchecked")
                            List<Element> properties = resultMap.elements();
                            for (Element prop : properties) {
                                if (prop != null && prop.attributeValue("property").equals(property)) {
                                    return prop.attributeValue("column");
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回ResultMap对应Element对象（取2次以上的时候，建议先把Element对象找到，再根据此Element对象再去找column，效率高很多）
     *
     * @param fileName 类对应的Mapper xml文件
     * @param id       唯一的id
     *                 <p>
     *                 如：resultMap id="BaseResultMap" type="com.chinagas.org.beans.User" 中的id
     *                 </p>
     * @return
     */
    public static Element getResultMapElement(String fileName, String id) {
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new File(fileName));
            if (document != null) {
                Element root = document.getRootElement();
                if (root != null) {
                    @SuppressWarnings("unchecked")
                    List<Element> resultMaps = root.elements("resultMap");
                    for (Element resultMap : resultMaps) {
                        if (resultMap != null && resultMap.attributeValue("id").equals(id)) {
                            return resultMap;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 在Element根据property找表的列名（和方法getResultMapElement()结合使用，多次取Column时效率高出很多倍）
     *
     * @param resultMapElement Mapper xml文件解析后得到的Element对象（方法：getResultMapElement()）
     * @param property         属性名（对应的Java对象属性名）
     * @return
     */
    public static String getMapperColumnByElement(Element resultMapElement, String property) {
        try {
            if (resultMapElement != null) {
                @SuppressWarnings("unchecked")
                List<Element> properties = resultMapElement.elements();
                for (Element prop : properties) {
                    if (prop != null && prop.attributeValue("property").equals(property)) {
                        return prop.attributeValue("column");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 检测mapperxml
     * */
    public static HashMap<String, String> getHashMapperColumnByElement(String fileName, String id) {

        try {
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            String filePath = String.format(mapperUrl, fileName);
            String inputStream = resourceLoader.getResource(filePath).getURL().getPath();

            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new File(inputStream));
            Element resultMapElement = null;
            if (document != null) {
                Element root = document.getRootElement();
                if (root != null) {
                    @SuppressWarnings("unchecked")
                    List<Element> resultMaps = root.elements("resultMap");
                    for (Element resultMap : resultMaps) {
                        if (resultMap != null && resultMap.attributeValue("id").equals(id)) {
                            resultMapElement = resultMap;
                            break;
                        }
                    }
                }
            }
            HashMap<String, String> hashMap = new HashMap<>();
            if (resultMapElement != null) {
                @SuppressWarnings("unchecked")
                List<Element> properties = resultMapElement.elements();
                for (Element prop : properties) {
                    if (prop != null && !prop.attributeValue("property").equals("")) {
                        //prop.attributeValue("column");
                        hashMap.put(prop.attributeValue("property"), prop.attributeValue("column"));
                    }
                }
                return hashMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /*
     *读取mapper属性节点
     */
    public static String getMapperColumnByElement(List<Element> lst, String property) {
        try {
            if (lst != null) {
                @SuppressWarnings("unchecked")
                List<Element> properties = lst;
                for (Element prop : properties) {
                    if (prop != null && prop.attributeValue("property").equals(property)) {
                        return prop.attributeValue("column");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 功能描述: 读取xml文件
     *
     * @Param: [xmlPath]
     * @Return: java.util.List<www.maxinhai.com.calculate.Formula>
     * @Author: XinHai.Ma
     * @Date: 2020/9/24 15:36
     */
    public static List<Object> ReadXml(String xmlPath) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(new File(xmlPath));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = doc.getRootElement();
        System.out.println("获取了根元素:" + root.getName());
        List<Element> list = root.elements();
        List<Object> empList = new ArrayList<Object>();
        for (Element element : list) {
            String name = element.element("key").getText();
            String value = element.element("value").getText();
            Object formula = new Object();
//            formula.setKey(name);
//            formula.setFormula(value);
            empList.add(formula);
        }
        return empList;
    }

}
