package com.ruoyi.gysl.login.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.gysl.entity.response.JgysbabResponse;

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

/**
 * 签名验证
 *
 * @author du
 * @since 2024/6/20 10:15
 */
public class StringUtil {
    public static void main(String[] args) {

    }

    public static List<JgysbabResponse> getFinalData(String content) throws Exception {
        String result = content.replaceAll(", pdfBase64=[^,}]*", "");
        //pdfbase64保存的集合
        List<String> segments = new ArrayList<>();
        Pattern pattern = Pattern.compile(", pdfBase64=([^,]+)");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            segments.add(matcher.group(1));
        }
        JSONObject newS = JSONObject.parseObject(result);
        // 1. 分割多个对象
        List<String> objects = splitObjects(newS.getString("data"));
        List<String> jsonObjects = new ArrayList<>();
        // 2. 遍历每个对象并解析
        for (String obj : objects) {
            jsonObjects.add(parseObject(obj));
        }
        // 3. 构建最终 JSON 数组
        String json = buildJsonArray(jsonObjects);
        JSONArray newArray = JSONArray.parseArray(json);
        // 转换为 Java 对象列表
        List<JgysbabResponse> returnData = new ArrayList<>();
        for (int i = 0; i < newArray.size(); i++) {
            JSONObject item = newArray.getJSONObject(i);
            JgysbabResponse res = item.toJavaObject(JgysbabResponse.class);
            res.setPdfBase64(segments.get(i));
            returnData.add(res);
        }
        return returnData;
    }

    /**
     * 分割输入字符串中的多个对象（支持嵌套结构）
     */
    private static List<String> splitObjects(String input) {
        List<String> objects = new ArrayList<>();
        int start = input.indexOf('{') + 1;
        int depth = 0;
        StringBuilder currentObj = new StringBuilder();

        for (int i = start; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '{') depth++;
            if (c == '}') {
                if (depth == 0) {
                    objects.add(currentObj.toString());
                    currentObj.setLength(0);
                    i++; // 跳过下一个逗号或闭合括号
                } else {
                    depth--;
                }
            }
            if (depth >= 0) currentObj.append(c);
        }
        return objects;
    }

    /**
     * 解析单个对象
     */
    private static String parseObject(String objStr) {
        List<String[]> keyValuePairs = new ArrayList<>();
        StringBuilder key = new StringBuilder();
        StringBuilder value = new StringBuilder();
        boolean isKey = true;
        boolean inQuotes = false;
        for (int i = 0; i < objStr.length(); i++) {
            char c = objStr.charAt(i);
            // 处理转义字符
            if (c == '\\' && i < objStr.length() - 1) {
                char next = objStr.charAt(++i);
                if (isKey) key.append(next);
                else value.append(next);
                continue;
            }
            // 处理引号
            if (c == '"') {
                inQuotes = !inQuotes;
                continue;
            }
            // 键值分隔符（不在引号内）
            if (c == '=' && !inQuotes && isKey) {
                isKey = false;
                continue;
            }
            // 键值对结束符（不在引号内）
            if (c == ',' && !inQuotes) {
                keyValuePairs.add(new String[]{key.toString().trim(), value.toString().trim()});
                key.setLength(0);
                value.setLength(0);
                isKey = true;
                continue;
            }
            // 积累字符
            if (isKey) key.append(c);
            else value.append(c);
        }

        // 添加最后一个键值对
        if (key.length() > 0) {
            keyValuePairs.add(new String[]{key.toString().trim(), value.toString().trim()});
        }

        return buildJsonObject(keyValuePairs);
    }

    /**
     * 构建单个 JSON 对象
     */
    private static String buildJsonObject(List<String[]> pairs) {
        StringBuilder json = new StringBuilder("{");
        for (int i = 0; i < pairs.size(); i++) {
            String[] pair = pairs.get(i);
            json.append('"')
                    .append(pair[0])
                    .append("\":\"")
                    .append(pair[1].replace("\"", "\\\"")) // 处理值中的双引号
                    .append('"');
            if (i < pairs.size() - 1) json.append(",");
        }
        return json.append("}").toString();
    }

    /**
     * 构建最终 JSON 数组
     */
    private static String buildJsonArray(List<String> objects) {
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < objects.size(); i++) {
            json.append(objects.get(i));
            if (i < objects.size() - 1) json.append(",");
        }
        return json.append("]").toString();
    }

}





