package cn.sikey.tools.util;

import cn.sikey.framework.common.exception.ServiceException;
import lombok.experimental.UtilityClass;
import org.apache.http.HttpStatus;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author: qin
 * @Date: 2025/3/25
 * @Description: 工具
 */
@UtilityClass
public class HisiUtils {

    /**
     * 对Map内所有value作utf8编码，拼接返回结果
     *
     * @param data
     * @return
     */
    public static String toQueryString(Map<String, Object> data) {
        try {
            StringBuilder queryString = new StringBuilder();
            for (Map.Entry<String, Object> pair : data.entrySet()) {
                queryString.append(percentEncode(pair.getKey())).append("=");
                queryString.append(percentEncode(String.valueOf(pair.getValue()))).append("&");
            }
            if (!queryString.isEmpty()) {
                queryString.deleteCharAt(queryString.length() - 1);
            }
            return queryString.toString();
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "参数utf8编码异常");
        }

    }

    /**
     * 编码工具方法
     *
     * @param param 参数
     * @return
     */
    private String percentEncode(String param) {
        try {
            return URLEncoder.encode(param, StandardCharsets.UTF_8).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "编码参数方法异常");
        }
    }

}