package com.kingdee.eas.custom.integration.base.util;

import com.kingdee.eas.custom.integration.base.exception.CommonErrorCodes;
import com.kingdee.eas.custom.integration.base.exception.IntegrationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {
    private static Logger logger = Logger.getLogger(HttpUtils.class);

    /**
     * 从URL中获取指定参数的值
     *
     * @param url 包含参数的URL字符串
     * @param key 要查找的参数名
     * @return 参数对应的值，如果未找到则返回空字符串
     */
    public static String getUrlParamValue(String url, String key) {
        String value = "";
        if (StringUtils.isNotBlank(url)) {
            int index = url.indexOf("?");
            if (index > 0) {
                url = url.substring(index + 1);
            }
            String[] params = url.split("&");

            for (String param : params) {
                String[] keyValue = param.split("=");
                if (key.equals(keyValue[0])) {
                    value = keyValue[1];
                    break;
                }
            }
        }

        return value;
    }

    /**
     * 从URL中获取指定参数的值集合
     *
     * @param url 包含参数的URL字符串
     * @return
     */
    public static Map<String, String> getUrlParamValueMap(String url) {
        Map<String, String> paramsMap = new HashMap<>();
        if (StringUtils.isNotBlank(url)) {
            int index = url.indexOf("?");
            if (index > 0) {
                url = url.substring(index + 1);
            }

            String[] params = url.split("&");

            for (String param : params) {
                String[] keyValue = param.split("=");
                if (keyValue.length == 2) {
                    paramsMap.put(keyValue[0], keyValue[1]);
                }
            }
        }

        return paramsMap;
    }

    /**
     * 从URL中获取指定参数的值集合
     *
     * @param url 包含参数的URL字符串
     * @return
     */
    public static String appendUrlParam(String url, Map<String, String> params) throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(url)) {
            logger.error("appendUrlParam URL为空");
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "URL为空");
        }

        if (params != null && !params.isEmpty()) {
            StringBuilder requestUrl = new StringBuilder(url);
            if (requestUrl.indexOf("?") < 0) {
                requestUrl.append("?");
            }
            boolean isFirstParam = requestUrl.indexOf("?") == requestUrl.length() - 1;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null) continue;
                String value = params.get(entry.getKey());
                if (!isFirstParam) {
                    requestUrl.append("&");
                }
                requestUrl.append(entry.getKey()).append("=")
                        .append(value != null ? URLEncoder.encode(value, StandardCharsets.UTF_8.name()) : "");
                isFirstParam = false;
            }
            url = requestUrl.toString();
        }
        logger.info("GET请求完整URL: " + url);
        return url;
    }
}
