package com.hfkj.channel.ccb.utils;

import com.hfkj.channel.weixin.utils.sdk.WXPayConstants;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

/**
 * @author hurui
 * 建行工具
 */
public class CCBUtils {

    /**
     * map转xml格式(多结构拼接生成)
     * @param sortedMap
     * @return
     */
    public static String mapToXml(Map<Object, Object> sortedMap) {
        StringBuilder builder = new StringBuilder();
        Iterator iterator = sortedMap.keySet().iterator();
        while (iterator.hasNext()) {

            Object key = (String) iterator.next();
            Object value = sortedMap.get(key);
            builder.append("<" + key + ">");
            if (value instanceof LinkedHashMap) {
                LinkedHashMap sortedMap1 = (LinkedHashMap) value;
                builder.append(mapToXml(sortedMap1));
            } else {
                builder.append(value);
            }
            builder.append("</" + key + ">");
        }
        return builder.toString();
    }


    /**
     * 将xml格式响应报文解析为Map格式
     *
     * @param responseXmlTemp
     * @return
     * @throws DocumentException
     */
    public static Map<String, Object> xml2map(String responseXmlTemp) throws DocumentException {
        Document doc = DocumentHelper.parseText(responseXmlTemp);
        Element rootElement = doc.getRootElement();
        Map<String, Object> mapXml = new HashMap<>();
        element2Map(mapXml, rootElement);
        return mapXml;
    }

    /**
     * 使用递归调用将多层级xml转为map
     *
     * @param map
     * @param rootElement
     */
    private static void element2Map(Map<String, Object> map, Element rootElement) {
        // 获得当前节点的子节点
        List<Element> childElements = rootElement.elements();
        if (childElements.size() > 0) {
            Map<String, Object> tempMap = new HashMap<>();
            for (Element e : childElements) {
                element2Map(tempMap, e);
                map.put(rootElement.getName(), tempMap);
            }
        } else {
            map.put(rootElement.getName(), rootElement.getText());
        }
    }

    /**
     * 生成加密字符串
     * @param param
     * @return
     */
    public static String paramSort(final Map<String, Object> param) {
        Set<String> keySet = param.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (StringUtils.isBlank(sb.toString())) {
                sb.append(k).append("=").append(param.get(k));
            } else {
                sb.append("&").append(k).append("=").append(param.get(k));
            }
        }
        return sb.toString();
    }

}
