package com.yida.data.common.core.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Objects;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 枚举工具类
 *
 * @author ZYJ
 * @date 2021/9/27
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class EnumUtils {

    /**
     * 值映射为枚举
     *
     * @param enumClass 枚举类
     * @param value     枚举值
     * @param method    取值方法
     * @param <E>       对应枚举
     * @return E
     * @author ZYJ
     * @date 2021/9/27 14:14
     */
    public static <E extends Enum<?>> E valueOf(Class<E> enumClass, Object value, Method method) {
        try {
            E[] es = enumClass.getEnumConstants();
            for (E e : es) {
                Object eValue;
                try {
                    method.setAccessible(true);
                    eValue = method.invoke(e);
                } catch (IllegalAccessException | InvocationTargetException e1) {
                    log.error("Error: NoSuchMethod in {}.  Cause:", enumClass.getName(), e1);
                    return null;
                }
                if (value instanceof Number && eValue instanceof Number
                    && new BigDecimal(String.valueOf(value)).compareTo(new BigDecimal(String.valueOf(eValue))) == 0) {
                    return e;
                }
                if (Objects.equals(eValue, value)) {
                    return e;
                }
            }
        } catch (Exception e) {
            
        }
        return null;
    }
}
