package com.ruoyi.web.v3.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.lang.reflect.Field;

public class QueryWrapperBuildUtil {

    public static String camelToUnderline(String camel) {
        return camel.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
    }

    public static <T, E> QueryWrapper<T> notNoneEqWrapperHelper(E entity) {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        if (entity == null) {
            return wrapper;
        }

        Class<?> clazz = entity.getClass();
        while (clazz != null && clazz != Object.class) {
            processClassFields(entity, clazz, wrapper);
            clazz = clazz.getSuperclass();
        }
        return wrapper;
    }

    private static <T, E> void processClassFields(E entity, Class<?> clazz, QueryWrapper<T> wrapper) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                if ("serialVersionUID".equals(field.getName())) {
                    continue;
                }
                field.setAccessible(true);
                Object value = field.get(entity);
                if (value != null) {
                    wrapper.eq(camelToUnderline(field.getName()), value);
                }
            } catch (IllegalAccessException e) {
                // 忽略无法访问的字段
            }
        }
    }

}
