package com.ycwl.basic.puzzle.fill.condition;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * 机位ID匹配条件策略
 * 判断指定的机位ID是否在当前上下文的机位列表中
 *
 * 支持两种匹配模式:
 * 1. 单个机位匹配: {"deviceId": 123}
 * 2. 多个机位匹配: {"deviceIds": [123, 456], "matchMode": "ALL"/"ANY"}
 *    - ALL: 所有指定的机位都必须存在
 *    - ANY: 至少存在一个指定的机位(默认)
 */
@Slf4j
@Component
public class DeviceIdMatchConditionStrategy implements ConditionStrategy {

    @Override
    public boolean evaluate(JsonNode conditionValue, ConditionContext context) {
        if (conditionValue == null) {
            log.warn("DEVICE_ID_MATCH条件值为null");
            return false;
        }

        List<Long> contextDeviceIds = context.getDeviceIds();
        if (contextDeviceIds == null || contextDeviceIds.isEmpty()) {
            log.debug("上下文中没有机位ID列表");
            return false;
        }

        // 单个机位匹配模式
        if (conditionValue.has("deviceId")) {
            Long requiredDeviceId = conditionValue.get("deviceId").asLong();
            boolean matched = contextDeviceIds.contains(requiredDeviceId);
            log.debug("单机位匹配: deviceId={}, matched={}", requiredDeviceId, matched);
            return matched;
        }

        // 多个机位匹配模式
        if (conditionValue.has("deviceIds")) {
            JsonNode deviceIdsNode = conditionValue.get("deviceIds");
            if (!deviceIdsNode.isArray()) {
                log.warn("deviceIds字段必须是数组");
                return false;
            }

            List<Long> requiredDeviceIds = new ArrayList<>();
            deviceIdsNode.forEach(node -> requiredDeviceIds.add(node.asLong()));

            if (requiredDeviceIds.isEmpty()) {
                log.warn("deviceIds数组为空");
                return false;
            }

            // 获取匹配模式,默认为ANY
            String matchMode = conditionValue.has("matchMode")
                    ? conditionValue.get("matchMode").asText()
                    : "ANY";

            boolean matched;
            if ("ALL".equalsIgnoreCase(matchMode)) {
                // ALL模式: 所有指定的机位都必须存在
                matched = contextDeviceIds.containsAll(requiredDeviceIds);
                log.debug("多机位ALL匹配: requiredDeviceIds={}, matched={}", requiredDeviceIds, matched);
            } else {
                // ANY模式: 至少存在一个指定的机位
                matched = requiredDeviceIds.stream().anyMatch(contextDeviceIds::contains);
                log.debug("多机位ANY匹配: requiredDeviceIds={}, matched={}", requiredDeviceIds, matched);
            }

            return matched;
        }

        log.warn("DEVICE_ID_MATCH条件缺少deviceId或deviceIds字段");
        return false;
    }

    @Override
    public String getSupportedType() {
        return "DEVICE_ID_MATCH";
    }
}
