package com.dcs.hnyz.utils;

import com.dcs.hnyz.domain.condition.Condition;
import com.dcs.hnyz.domain.condition.ConditionGroup;
import com.dcs.hnyz.domain.condition.ConditionItem;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.util.ArrayList;
import java.util.List;

/**
 * ConditionParser
 * 条件解析器
 * @author: hmy
 * @date: 2025/5/27 9:55
 */
public class ConditionParser {

    private static final ObjectMapper mapper = new ObjectMapper();

    public static Condition parse(JsonNode node) {
        if (node == null || node.isNull() || !node.has("type")) {
            throw new IllegalArgumentException("无效的条件节点：缺少 type 字段或节点为 null");
        }
        String type = node.get("type").asText();
        if ("group".equals(type)) {
            ConditionGroup group = new ConditionGroup();
            group.setOperator(node.get("operator").asText());
            ArrayNode children = (ArrayNode) node.get("conditions");
            List<Condition> conditionList = new ArrayList<>();
            for (JsonNode child : children) {
                conditionList.add(parse(child));
            }
            group.setConditions(conditionList);
            return group;
        } else if ("item".equals(type)) {
            ConditionItem item = new ConditionItem();
            item.setDevice(node.get("equipmentId").asInt());
            item.setOperator(node.get("operator").asText());
            item.setValue(node.get("value").asText());
            return item;
        }
        throw new IllegalArgumentException("Unknown condition type: " + type);
    }

    /**
     * 从 JSON 字符串解析为 Condition 对象
     */
    public static Condition fromJsonString(String jsonStr) throws Exception {
        JsonNode root = mapper.readTree(jsonStr);
        return parse(root);
    }
}
