package thyyxxk.webserver.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import thyyxxk.webserver.entity.CodeName;

import java.util.List;

public class EmrJsonUtils {
    public static String businessCodeValueStr(String jsonStr, String businessCode) {
        if (StrUtil.isBlank(jsonStr)) {
            return "";
        }
        JSONObject jsonValue = JSONUtil.toBean(jsonStr, JSONObject.class);
        List<CodeName> codeNames = analysisValueIsArr(jsonValue, businessCode);
        if (ListUtil.notBlank(codeNames)) {
            return codeNames.get(0).getName();
        }
        String value = analysisValueIsStr(jsonValue, businessCode);
        if (!"null".equals(value)) {
            return value;
        }
        return "";
    }

    /**
     * 返回值如果是 "null" 就说明报错了
     *
     * @param json         json 数据
     * @param businessCode 业务编码
     * @return
     */
    public static String analysisValueIsStr(JSONObject json, String businessCode) {
        try {
            return json.getByPath(businessCode + ".value", String.class);
        } catch (Exception e) {
            return "null";
        }
    }

    public static List<CodeName> analysisValueIsArr(JSONObject json, String businessCode) {
        try {
            return json.getByPath(businessCode + ".value", JSONArray.class).toList(CodeName.class);
        } catch (Exception e1) {
            return null;
        }
    }

}
