package com.storlead.sales.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class SafeJsonParser {

    public static JSONObject parseSafely(String jsonStr) {
        try {
            // 先尝试正常解析
            return JSON.parseObject(jsonStr);
        } catch (com.alibaba.fastjson.JSONException e) {
            // 如果解析失败，尝试修复JSON
            String fixedJson = fixJsonString(jsonStr);
            return JSON.parseObject(fixedJson);
        }
    }

    private static String fixJsonString(String jsonStr) {
        // 找到并修复sketchDataJson字段
        StringBuilder sb = new StringBuilder(jsonStr);
        String searchStr = "\"sketchDataJson\":\"{";

        int startPos = 0;
        while ((startPos = sb.indexOf(searchStr, startPos)) != -1) {
            int jsonStart = startPos + searchStr.length() - 1; // 指向第一个{
            int jsonEnd = findMatchingBrace(sb, jsonStart);

            if (jsonEnd != -1) {
                // 提取sketchDataJson的内容
                String innerJson = sb.substring(jsonStart + 1, jsonEnd);
                // 对内容中的双引号进行转义
                String escapedInnerJson = innerJson.replace("\"", "\\\"");
                // 替换原来的内容
                sb.replace(jsonStart + 1, jsonEnd, escapedInnerJson);
                startPos = jsonEnd + escapedInnerJson.length() - innerJson.length();
            } else {
                break;
            }
        }

        return sb.toString();
    }

    private static int findMatchingBrace(StringBuilder sb, int start) {
        int braceCount = 1;
        for (int i = start + 1; i < sb.length(); i++) {
            char c = sb.charAt(i);
            if (c == '{') {
                braceCount++;
            } else if (c == '}') {
                braceCount--;
                if (braceCount == 0) {
                    return i;
                }
            }
        }
        return -1;
    }
}
