package org.jeecg.common.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @description:
 * @author: niugeng
 * @create: 2024-03-04 18:03
 **/
@Slf4j
public class JsonPathUtil {


    /**
     * 替换指定节点的值
     * @param json
     * @param node 节点
     * @param value 值
     * @return {@link String}
     */
    public static String replaceJsonStr(String json,String node ,String value) {
        try {
            if (StrUtil.isBlank(json)){
                return json;
            }
            if (!StrUtil.contains(json,node)){
                return json;
            }

            // 解析 JSON
            DocumentContext document = JsonPath.parse(json);
            // 获取要替换的节点的路径
            String path = "$.."+node;
            // 执行节点替换操作
            document.map(path, (currentValue, configuration) -> {
                // 数据处理，返回替换后的内容
                return value;
            });

            // 获取更新后的 JSON
            return document.jsonString();
        } catch (Exception e) {
          log.error("转换失败:",e);
          return json;
        }
    }

    /**
     * 获取指定节点的值
     * @param json
     * @param node
     * @return {@link String}
     */
    public static String queryJsonStr(String json,String node) {
        try {
            List<String> list = JsonPath.read(json, "$.."+node);
            if (list.isEmpty()){
                return "";
            }
            return list.get(0);

        } catch (Exception e) {
            return "";
        }
    }


    public static void main(String[] args) {
        System.out.println( DateUtil.format(DateUtil.lastMonth(),"yyyy-MM"));

        String json = "[{\n" +
                "\t\"nsrsbh\": \"纳税人识别号/统一社会信用代码\",\n" +
                "\t\"lysl\": \"1\",\n" +
                "\t\"ywlsh\": \"业务流水号\",\n" +
                "\t\"list\": [\n" +
                "\t\t{\n" +
                "\t\t\t\"nsrsbh\": \"222\"\n" +
                "\t\t}\n" +
                "\t]\n" +
                "}]";

        System.out.println(json);

        String updatedJson = replaceJsonStr(json,"nsrsbh1","1");
        System.out.println(updatedJson);

        System.out.println(queryJsonStr(json,"lysl"));
    }


}
