package com.zcloud.fire.check.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @author fangjiakai
 * @date 2025/10/20 11:54
 */
public class PageQueryHelper {
    private static final Pattern PATTERN = Pattern.compile("([a-z])([A-Z])");

    /**
     * 创建分页查询包装器
     *
     * @param queryWrapper 查询包装器
     * @param pageQuery    分页查询参数
     * @return 构建好查询条件的QueryWrapper
     */
    public static <T> QueryWrapper<T> createPageQueryWrapper(QueryWrapper<T> queryWrapper, Map<String, Object> pageQuery) {
        if (pageQuery == null || pageQuery.isEmpty()) {
            return queryWrapper;
        }

        for (Map.Entry<String, Object> entry : pageQuery.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            // 忽略空值
            if (value == null || StringUtils.isBlank(value.toString())) {
                continue;
            }

            // 处理不同类型的查询条件
            if (key.startsWith("like")) {
                String columnName = toUnderlineName(key.substring(4)); // 去掉 "like" 前缀
                queryWrapper.like(columnName, value);
            } else if (key.startsWith("eq")) {
                String columnName = toUnderlineName(key.substring(2)); // 去掉 "eq" 前缀
                queryWrapper.eq(columnName, value);
            } else if (key.startsWith("gt")) {
                String columnName = toUnderlineName(key.substring(2)); // 去掉 "gt" 前缀
                queryWrapper.gt(columnName, value);
            } else if (key.startsWith("lt")) {
                String columnName = toUnderlineName(key.substring(2)); // 去掉 "lt" 前缀
                queryWrapper.lt(columnName, value);
            } else if (key.startsWith("ge")) {
                String columnName = toUnderlineName(key.substring(2)); // 去掉 "ge" 前缀
                queryWrapper.ge(columnName, value);
            } else if (key.startsWith("le")) {
                String columnName = toUnderlineName(key.substring(2)); // 去掉 "le" 前缀
                queryWrapper.le(columnName, value);
            } else if (key.startsWith("ne")) {
                String columnName = toUnderlineName(key.substring(2)); // 去掉 "ne" 前缀
                queryWrapper.ne(columnName, value);
            }
        }

        return queryWrapper;
    }

    /**
     * 将驼峰命名转换为下划线命名
     *
     * @param camelCaseName 驼峰命名字符串
     * @return 下划线命名字符串
     */
    private static String toUnderlineName(String camelCaseName) {
        Matcher matcher = PATTERN.matcher(camelCaseName);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1) + "_" + matcher.group(2).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString().toLowerCase();
    }
}
