package com.common.service;



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

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@Service
@RequiredArgsConstructor
public class LogDataCompleteService {


    /**
     * 处理日志数据补全
     */
    public boolean processDataCompletion(String ruleContent,Map<String, Object> destMap) {
        try {
            boolean hasCompleted = false;
            if (executeCompleteRule(ruleContent, destMap)) {
                    hasCompleted = true;
            }
            if (hasCompleted) {
                log.debug("数据补全完成: {}", destMap.get("id"));
            } else {
                log.debug("数据无需补全: {}", destMap.get("id"));
            }
            return hasCompleted;
        } catch (Exception e) {
            log.error("处理数据补全时发生错误: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 执行补全规则
     */
    private boolean executeCompleteRule(String ruleContent, Map<String, Object> destMap) {
        try {
            JSONObject ruleJson = JSON.parseObject(ruleContent);
            JSONArray completeColumns = ruleJson.getJSONArray("complete_columns");

            if (completeColumns == null || completeColumns.isEmpty()) {
                log.warn("补全规则为空");
                return false;
            }

            boolean hasCompleted = false;

            // 遍历所有补全配置
            for (int i = 0; i < completeColumns.size(); i++) {
                JSONObject completeConfig = completeColumns.getJSONObject(i);
                 if (executeCompleteConfig(completeConfig, destMap)) {
                    hasCompleted = true;
                }
            }

            return hasCompleted;

        } catch (Exception e) {
            log.error("解析补全规则失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 执行单个补全配置
     */
    private boolean executeCompleteConfig(JSONObject completeConfig, Map<String, Object> destMap) {
        try {
            String columnName = completeConfig.getString("column_name");
            Object value = completeConfig.get("value");
            JSONArray conditions = completeConfig.getJSONArray("conditions");
            String relation = completeConfig.getString("filters_relation");

            // 检查目标字段是否已存在
            if (destMap.containsKey(columnName) && destMap.get(columnName) != null) {
                log.debug("字段 {} 已存在，跳过补全", columnName);
                return false;
            }

            // 检查条件是否满足
            boolean conditionsMet = evaluateConditions(conditions, relation, destMap);

            if (conditionsMet) {
                // 执行补全操作
                destMap.put(columnName, value);
                log.debug("字段 {} 补全完成，值: {}", columnName, value);
                return true;
            }

            return false;

        } catch (Exception e) {
            log.error("执行补全配置失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 评估条件
     */
    private boolean evaluateConditions(JSONArray conditions, String relation, Map<String, Object> destMap) {
        if (conditions == null || conditions.isEmpty()) {
            return true; // 无条件，直接通过
        }

        // 根据关系类型评估
        if ("or".equalsIgnoreCase(relation)) {
            return evaluateOrConditions(conditions, destMap);
        } else {
            // 默认使用 AND 关系
            return evaluateAndConditions(conditions, destMap);
        }
    }

    /**
     * 评估 AND 关系的条件
     */
    private boolean evaluateAndConditions(JSONArray conditions, Map<String, Object> destMap) {
        for (int i = 0; i < conditions.size(); i++) {
            JSONObject condition = conditions.getJSONObject(i);
            if (!evaluateCondition(condition, destMap)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 评估 OR 关系的条件
     */
    private boolean evaluateOrConditions(JSONArray conditions, Map<String, Object> destMap) {
        for (int i = 0; i < conditions.size(); i++) {
            JSONObject condition = conditions.getJSONObject(i);
            if (evaluateCondition(condition, destMap)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 评估单个条件
     */
    private boolean evaluateCondition(JSONObject condition, Map<String, Object> destMap) {
        String columnName = condition.getString("column_name");
        String op = condition.getString("op");
        Object value = condition.get("value");

        // 从目标Map中获取字段值
        Object fieldValue = destMap.get(columnName);
        if (fieldValue == null) {
            fieldValue = ""; // 处理null值
        }

        String fieldValueStr = fieldValue.toString();

        try {
            switch (op) {
                case "=":
                    return equals(fieldValueStr, value);
                case "!=":
                    return notEquals(fieldValueStr, value);
                case "in":
                    return in(fieldValueStr, value);
                case "zero_len":
                    return zeroLen(fieldValueStr, value);
                case "contain":
                    return contain(fieldValueStr, value);
                case "regexp":
                    return regexp(fieldValueStr, value);
                default:
                    log.warn("未知的操作符: {}", op);
                    return false;
            }
        } catch (Exception e) {
            log.error("评估条件失败: {}{}{}, 错误: {}", columnName, op, value, e.getMessage());
            return false;
        }
    }

    /**
     * 等于操作
     */
    private boolean equals(String fieldValue, Object value) {
        if (value == null) return false;
        return fieldValue.equals(value.toString());
    }

    /**
     * 不等于操作
     */
    private boolean notEquals(String fieldValue, Object value) {
        if (value == null) return true;
        return !fieldValue.equals(value.toString());
    }

    /**
     * IN 操作
     */
    private boolean in(String fieldValue, Object value) {
        if (value instanceof JSONArray) {
            JSONArray array = (JSONArray) value;
            for (Object item : array) {
                if (fieldValue.equals(item.toString())) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    /**
     * 非空检查操作
     */
    private boolean zeroLen(String fieldValue, Object value) {
        boolean isEmpty = !StringUtils.hasText(fieldValue);
        boolean expected = Boolean.parseBoolean(value.toString());
        return isEmpty == expected;
    }

    /**
     * 包含操作
     */
    private boolean contain(String fieldValue, Object value) {
        if (value == null) return false;
        return fieldValue.contains(value.toString());
    }

    /**
     * 正则表达式匹配
     */
    private boolean regexp(String fieldValue, Object value) {
        if (value == null) return false;
        try {
            Pattern pattern = Pattern.compile(value.toString());
            return pattern.matcher(fieldValue).matches();
        } catch (Exception e) {
            log.error("正则表达式编译失败: {}, 错误: {}", value, e.getMessage());
            return false;
        }
    }



}