package com.jianshui.common.utils;

import cn.hutool.core.bean.BeanUtil;

import java.util.Map;

/**
* @Author: kk
* @Description: 将类转换为小写
* @DateTime: 2023/5/23 16:44
* @Params:
* @Return
*/
public class ToLowerBeanUtil {

    /**
     * 获取对象属性值-忽略大小写
     *
     * @param bean      对象
     * @param fieldName 属性名
     * @return 属性值
     */
    public static Object getPropertyIgnoreCase(Object bean, String fieldName) {
        if (bean == null) {
            return null;
        }

        Map<String, Object> map = BeanUtil.beanToMap(bean, false, true);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().toLowerCase().equals(fieldName.toLowerCase())) {
                return entry.getValue();
            }
        }

        return null;
    }

    /**
     * 将Bean的属性名转为小写
     *
     * @param bean 对象
     */
    public static void toLowerCase(Object bean) {
        if (bean == null) {
            return;
        }

        Map<String, Object> map = BeanUtil.beanToMap(bean, false, true);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            if (!key.equals(key.toLowerCase())) {
                Object value = entry.getValue();
                BeanUtil.setFieldValue(bean, key, null);
                BeanUtil.setFieldValue(bean, key.toLowerCase(), value);
            }
        }
    }



}
