package com.ruoyi.common.core.enums;

import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;

/**
 * @Description: 枚举数据校验接口
 * @Author: wenhao
 * @Create: 2022/08/14 11:04
 * @Version: 1.0
 */
public interface BaseValidEnum<T> {

    String VALUES_METHOD = "values";

    T getCode();

    String getDesc();

    // 根据code获取枚举类实例
    @SneakyThrows(ReflectiveOperationException.class)
    static <T> BaseValidEnum<T> getByCode(T code, Class<?> clazz) {
        Method valuesMethod = clazz.getMethod(VALUES_METHOD);
        BaseValidEnum<T>[] validEnums = (BaseValidEnum<T>[]) valuesMethod.invoke(null);
        for (BaseValidEnum<T> value : validEnums) {
            if (StringUtils.equals(String.valueOf(value.getCode()), String.valueOf(code))) {
                return value;
            }
        }
//        ExceptionCast.cast(String.format("请检查code:%s对应明细值是否配置", code));
        return null;
    }

    // 根据desc获取枚举类实例
    @SneakyThrows(ReflectiveOperationException.class)
    static <T> BaseValidEnum<T> getByDesc(String desc, Class<?> clazz) {
        Method valuesMethod = clazz.getMethod(VALUES_METHOD);
        BaseValidEnum<T>[] validEnums = (BaseValidEnum<T>[]) valuesMethod.invoke(null);
        for (BaseValidEnum<T> value : validEnums) {
            if (StringUtils.equals(value.getDesc(), desc)) {
                return value;
            }
        }
//        ExceptionCast.cast(String.format("请检查desc:%s对应明细值是否配置", code));
        return null;
    }

}
