package com.ruoyi.framework.converter;

import com.ruoyi.project.system.enums.BaseEnum;
import io.netty.util.internal.ObjectUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.core.convert.converter.Converter;
import springfox.documentation.schema.Maps;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class IntegerToEnumConverter<T extends BaseEnum> implements Converter<String, T> {

    private Map<String, T> enumMap = new HashMap<>();
    private Map<String, T> StringEnumMap = new HashMap<>();

    public IntegerToEnumConverter(Class<T> enumType) {
        Arrays.stream(enumType.getEnumConstants())
                .forEach(x -> {
                    enumMap.put(x.getCode().toString(), x);
                    StringEnumMap.put(x.getValue(), x);
                });
    }

    @Override
    public T convert(String source) {
        return Optional.of(source)
                .map(enumMap::get)
                .orElseGet(() -> Optional.of(source)
                        .map(StringEnumMap::get)
                        .orElseThrow(() -> new IllegalArgumentException("无法匹配对应的枚举类型")));
    }
}
