package com.xunhong.erp.turbo.base.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UrlUtils {
	public static String queryParam(String url, String paramName) {
		// 正则表达式模式：匹配 paramName 及其对应的值
		String regex = "[?&]" + paramName + "=([^&]*)";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(url);

		if (matcher.find()) {
			return matcher.group(1);
		}
		return null;
	}

	public static String appendParam(String url, String paramName, String paramValue) {
		if (url == null || paramName == null || paramValue == null) {
			throw new IllegalArgumentException("Base URL, parameter name, and parameter value cannot be null");
		}

		StringBuilder newUrlBuilder = new StringBuilder(url);

		if (url.contains("?")) {
			newUrlBuilder.append("&").append(paramName).append("=").append(paramValue);
		} else {
			newUrlBuilder.append("?").append(paramName).append("=").append(paramValue);
		}

		return newUrlBuilder.toString();
	}

	// 替换
	public static String replaceParam(String url, String paramName, String paramValue) {
		if (url == null || paramName == null || paramValue == null) {
			throw new IllegalArgumentException("Base URL, parameter name, and parameter value cannot be null");
		}

		String regex = "[?&]" + Pattern.quote(paramName) + "=([^&]*)";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(url);

		StringBuilder newUrlBuilder = new StringBuilder(url);
		if (matcher.find()) {
			newUrlBuilder.replace(matcher.start(), matcher.end(), paramName + "=" + paramValue);
		} else {
			newUrlBuilder.append("?").append(paramName).append("=").append(paramValue);
		}

		return newUrlBuilder.toString();
	}
}
