package com.njcn.mysql.util;

import cn.hutool.core.util.ObjectUtil;
import com.njcn.mysql.bo.util.CompareValue;

import java.lang.reflect.Field;

//防止数据过大
public class MaxValueProcessor {
    public static void process(Object obj) {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(CompareValue.class)) {
                CompareValue compareValue = field.getAnnotation(CompareValue.class);
                field.setAccessible(true);
                Class<?> type = field.getType();
                try {
                    if (type == Float.class) {
                        Float fieldValue = (Float) field.get(obj);
                        float minValue = compareValue.minValue();
                        float maxValue = compareValue.maxValue();
                        if(ObjectUtil.isNotNull(fieldValue)){
                            if (fieldValue > maxValue) {
                                field.set(obj, maxValue);
                            }
                            if (fieldValue < minValue) {
                                field.set(obj, minValue);
                            }
                        }
                    }
                    if (type == Double.class) {
                        Double fieldValue = (Double) field.get(obj);
                        double minValue = compareValue.minValue();
                        double maxValue = compareValue.maxValue();
                        if(ObjectUtil.isNotNull(fieldValue)){
                            if (fieldValue > maxValue) {
                                field.set(obj, maxValue);
                            }
                            if (fieldValue < minValue) {
                                field.set(obj, minValue);
                            }
                        }
                    }
                    if (type == Integer.class) {
                        Integer fieldValue = (Integer) field.get(obj);
                        int minValue = (int) compareValue.minValue();
                        int maxValue = (int) compareValue.maxValue();
                        if(ObjectUtil.isNotNull(fieldValue)){
                            if (fieldValue > maxValue) {
                                field.set(obj, maxValue);
                            }
                            if (fieldValue < minValue) {
                                field.set(obj, minValue);
                            }
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}