package com.fjhx.common.utils;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class Utils {

    /**
     * 请求API工具方法
     */
    public static JSONObject getJSON(HttpRequestBase httpRequestBase) throws IOException {
        HttpClient client = HttpClients.createDefault();
        httpRequestBase.setConfig(RequestConfig.custom().setConnectTimeout(3000).build());
        HttpResponse response = client.execute(httpRequestBase);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        String responseStr = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8);
        if (statusCode != 200) {
            log.error("请求失败 {} {} {}", statusCode, httpRequestBase.getURI(), responseStr);
        }
        return JSONObject.parseObject(responseStr);
    }

    /**
     * 赋值新的变更编号
     */
    public static String getNewCode(String code) {
        Matcher matcher = Pattern.compile(".*\\((.*?)\\)$").matcher(code);
        int index = 2;
        if (matcher.find()) {
            index = (Integer.parseInt(matcher.group(1)) + 1);
            code = code.substring(0, code.lastIndexOf("("));
        }
        return code + "(" + index + ")";
    }
}
