package com.xjrsoft.common.utils;

import java.lang.reflect.Field;
import java.sql.Time;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author dzx
 * @date 2024/6/14
 */
public class SqlRunnerAdapterUtil {
    /**
     * 将下划线转换为驼峰
     * @param input
     * @return
     */
    public static String underscoreToCamel(String input) {
        if (input == null) {
            return input;
        }

        StringBuilder builder = new StringBuilder();
        boolean nextUpperCase = false;

        for (char c : input.toCharArray()) {
            if (c == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    builder.append(Character.toUpperCase(c));
                    nextUpperCase = false;
                } else {
                    builder.append(Character.toLowerCase(c));
                }
            }
        }

        return builder.toString();
    }

    /**
     * 将驼峰转下划线
     * @param camelCaseStr
     * @return
     */
    public static String toUnderScoreCase(String camelCaseStr) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < camelCaseStr.length(); i++) {
            char c = camelCaseStr.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i > 0) {
                    builder.append('_');
                }
                builder.append(Character.toLowerCase(c));
            } else {
                builder.append(c);
            }
        }
        return builder.toString();
    }


    public static <T> T convertMapToEntity(Map<String, Object> map, Class<T> entityClass) {
        T entity;
        try {
            entity = entityClass.newInstance();
            Field[] fields = entityClass.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                String mapKey = toUnderScoreCase(fieldName);
                if (map.containsKey(mapKey)) {
                    field.setAccessible(true);
                    field.set(entity, map.get(mapKey));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Error converting map to entity", e);
        }
        return entity;
    }

    public static String[] convertMapToStringArray(Map<String, Object> map) {
        List<String> dataList = new ArrayList<>();
        for (Object value : map.values()) {
            dataList.add(value == null ? "" : value.toString());
        }

        return dataList.toArray(new String[dataList.size()]);
    }

    public static Integer[] convertMapToIntegerArray(Map<String, Object> map) {
        List<Integer> dataList = new ArrayList<>();
        for (Object value : map.values()) {
            dataList.add(value == null ? null : Integer.parseInt(value.toString()));
        }

        return dataList.toArray(new Integer[dataList.size()]);
    }

}
